Save NSArray of Class to cacheDirectory

一世执手 提交于 2019-11-29 16:53:54

Xcode 7.3.1 • Swift 2.2.1

You can make your Dog class NSCoding compliant:

class Dog: NSObject, NSCoding {
    let id: Int
    let name: String
    required init(id: Int, name: String) {
        self.id = id
        self.name = name
    }
    required init(coder decoder: NSCoder){
        self.id = decoder.decodeObjectForKey("id") as? Int ?? 0
        self.name = decoder.decodeObjectForKey("name") as? String ?? ""
    }
    func encodeWithCoder(coder: NSCoder) {
        coder.encodeObject(id, forKey: "id")
        coder.encodeObject(name, forKey: "name")
    }
}

Then you can save your array data to disk as follow:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let dog1 = Dog(id: 1, name: "taro")
        let dog2 = Dog(id: 2, name: "jiro")
        do {
            let cachesDirectoryURL = try NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
            let array = [dog1, dog2]
            let fileURL = cachesDirectoryURL.URLByAppendingPathComponent("CachedQuestions.plist")
            let success = NSKeyedArchiver.archiveRootObject(array, toFile: fileURL.path!)
            print(success)
            // to load it from disk
            if let loadedArray = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [Dog] {
                print(loadedArray.count)   // 2
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!