How to use persist & retrieve an NSCoding compliant object to app Document directory in Swift 3?

后端 未结 2 1218
执念已碎
执念已碎 2021-01-15 20:49

Here\'s a NSCoding compliant object. I would like to save and recover it from the app\'s documents directory in Swift 3. I imagine it\'s a save method and recover method. Ho

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 21:25

    Saving:

    // Get documents directory
    if let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
    
        // Append your file name to the directory path
        let path = (docs as NSString).appendingPathComponent("filename")
    
        // Archive your object to a file at that path
        NSKeyedArchiver.archiveRootObject(yourObject, toFile: path)
    }
    

    Loading:

    // Get documents directory
    if let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
    
        // Append your file name to the directory path
        let path = (docs as NSString).appendingPathComponent("filename")
    
        // Unarchive your object from the file
        let yourObject = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? Book
    
        // do whatever with yourObject
    }
    

提交回复
热议问题