iOS数据存储 - Archiver



  • Swift版本: 4.0

    使用 NSKeyedArchiver 可以存储一些自定义的数据类型。

    • 定义需要Archive的数据类型MyData,需继承NSObject,并实现NSCoding协议。
    class MyData: NSObject, NSCoding {
        var name: String
        var age: Int
        
        init(name: String, age: Int) {
            self.name = name
            self.age = age
        }
        
        required init?(coder aDecoder: NSCoder) {
            self.name = (aDecoder.decodeObject(forKey: "name") as? String) ?? ""
            self.age = aDecoder.decodeInteger(forKey: "age")
        }
        
        func encode(with aCoder: NSCoder) {
            aCoder.encode(name, forKey: "name")
            aCoder.encode(age, forKey: "age")
        }
    }
    
    • 定义存储路径
    var filePath: String {
        let manager = FileManager.default
        let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first! as URL
        return url.appendingPathComponent("objects").path
    }
    
    • 存储数据
    // save
    let myData = MyData(name: "Sheldon", age: 18)
    let testFilePath = filePath
    NSKeyedArchiver.archiveRootObject(myData, toFile: testFilePath)
    
    • 获取数据
    // get
    let testFilePath = filePath
    let value2 = NSKeyedUnarchiver.unarchiveObject(withFile: testFilePath) as? MyData
    
    print("value2 = \(value2!.name, value2!.age)")
    
    • 删除数据
    // remove
    let testFilePath = filePath
    if FileManager.default.fileExists(atPath: testFilePath) {
        do {
            try FileManager.default.removeItem(atPath: testFilePath)
        } catch {
            print("error")
        }
    }
    

    Demo源码

    https://github.com/CaryZheng/iOSTutorials


Log in to reply