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

后端 未结 2 1219
执念已碎
执念已碎 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:05

    Here's the same design using guard statements.

    import UIKit
    import MediaPlayer
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let book = Book(title: "Atlas Shrugged", author: "Ayn Rand", pageCount: 10, categories: ["Ethics"], available: true)
            save(object: book, filename: "Bookshelf")
    
            let atlasShrugged = retrieve(filename: "Bookshelf") as! Book
            print("\(atlasShrugged.title) by \(atlasShrugged.author)")
        }
    
        func save(object:NSObject ,filename:String){
    
            //build filepath in doc directory
            guard let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return }
            let path = (docs as NSString).appendingPathComponent(filename)
    
            //save object to path in docs
            NSKeyedArchiver.archiveRootObject(object, toFile: path)
        }
    
        func retrieve(filename:String) -> AnyObject? {
    
            // Get documents directory
            guard let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return nil }
            //build path to file
            let path = (docs as NSString).appendingPathComponent(filename)
            //Unarchive from doc directory
            let object = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? Book
            return object
        }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题