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
"
// to load it from disk
if let dogs = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(Data(contentsOf: fileURL)) as? [Dog] {
print(dogs.count) // 2
}
} catch {
print(error)
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…