Save NSArray of Class to cacheDirectory

最后都变了- 提交于 2019-11-28 10:26:50

问题


I'd like to NSArray of Class to the cacheDirectory. I've wrote as following, however it returns false. Could you tell me how to solve this problem? Thank you for your kindness.

let paths2 = NSSearchPathForDirectoriesInDomains(
        .CachesDirectory,
        .UserDomainMask, true)
    let cachesPath: AnyObject = paths2[0]

    var cachedQuestions:NSArray = questions as NSArray
    let filePath = cachesPath.stringByAppendingPathComponent("CachedQuestions")

    class Dog {
        var id:Int?
        var name:String?
        init(id:Int, name:String) {
            self.id = id
            self.name = name
        }
    }

    var dogs = [Dog]()
    dogs.append(Dog(id:1, name:"taro"))
    dogs.append(Dog(id:2, name:"jiro"))
    var nsArrayDogs:NSArray = dogs as NSArray

    let success = nsArrayDogs.writeToFile(filePath, atomically: true)

    if success {
        println("save success")
    }

回答1:


Xcode 11 • Swift 5.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.decodeInteger(forKey: "id")
        self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
    }
    func encode(with coder: NSCoder) {
        coder.encode(id, forKey: "id")
        coder.encode(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 FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            let array = [dog1, dog2]
            let fileURL = cachesDirectoryURL.appendingPathComponent("CachedQuestions.plist")
            let data = try NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: false)
            try data.write(to: fileURL)
            print("saved")  // "saved\n"
            // to load it from disk
            if let dogs = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(Data(contentsOf: fileURL)) as? [Dog] {
                print(dogs.count)   // 2
            }
        } catch {
            print(error)
        }
    }
}


来源:https://stackoverflow.com/questions/32420335/save-nsarray-of-class-to-cachedirectory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!