将 Class 的 NSArray 保存到 cacheDirectory

Save NSArray of Class to cacheDirectory

我想 Class 的 NSArray 到 cacheDirectory。我写了如下,但它 returns 错误。你能告诉我如何解决这个问题吗?谢谢你的好意。

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")
    }

Xcode 11 • Swift 5.1

您可以使您的狗 class 符合 NSCoding 标准:

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")
    }
}

然后您可以将阵列数据保存到磁盘,如下所示:

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)
        }
    }
}