iOS 数据本地持久化存储

1,034 阅读1分钟

一、归档(NSKeyedArchiver)

Apple开发者文档传送点(理论知识)

下面代码我存储的是数组,数组里的类型是我自定义对象

使用方式(swift):

    //路径
    var filePath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, .userDomainMask, true).last ?? "").appending("/archieve")
    
    //保存数据
    static func saveData(array: Array<Model>) {
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: true)
            do {
                _ = try data.write(to: URL(fileURLWithPath: filePath), options: .atomic)
            } catch {
                print(error)
            }
        } catch {
        }
    }

    //获取数据    
    static func getData() -> Array<Model>{
        do {
            let data = try Data.init(contentsOf: URL(fileURLWithPath: filePath))
            let Models = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? Array<Model>
            return Models ?? Array<Model>()
        } catch {
        }
        return Array<Model>()
    }

自定义Model(这里则需要注意)

class Model: NSObject, NSCoding, NSSecureCoding{
    static var supportsSecureCoding: Bool = true
    var content: String
    var time: String

    init(content: String, time: String) {
        self.content = content
        self.time = time
    }

    func encode(with coder: NSCoder) {
        coder.encode(self.content, forKey: "content")
        coder.encode(self.time, forKey: "time")
    }

    required init?(coder: NSCoder) {
        self.content = coder.decodeObject(forKey: "content") as! String
        self.time = coder.decodeObject(forKey: "time") as! String
    }
}