I need to save and load a nest of Array of Dictionaries of Dictionaries of array of mYClassInstances.
How should I store this object?
You cannot store Swift classes directly in a property list. You could store enough information about a class to reconstruct it later but I don't think that is what you are asking for. If you want to store an arbitrary graph of objects in a file, Cocoa offers the NSKeyedArchiver/Unarchiver classes.
Make sure that your MyClassInstance class is derived from NSObject and that it supports the NSCoding protocol. For example,
class MyClassInstances: NSObject, NSCoding, Printable {
let name: String
init(name: String) {
self.name = name
}
@objc func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "NAME")
}
@objc required init(coder decoder: NSCoder) {
self.name = decoder.decodeObjectForKey("NAME") as! String
}
override var description: String {
return "MyClassInstance.name = \(name)"
}
}
Then assuming you have your array of dictionaries, of dictionaries, of arrays of instances stored in a variable named nest; you would could store all of your objects with this call.
let temporaryDirectory = NSTemporaryDirectory()
let temporaryFile = temporaryDirectory.stringByAppendingPathComponent("SO-test.archive")
NSKeyedArchiver.archiveRootObject(nest, toFile: temporaryFile)
Reading back the graph of objects uses this call. Note that it is important to get the typecasting correct.
let nest2 = NSKeyedUnarchiver.unarchiveObjectWithFile(temporaryFile) as! [[String: [String: [MyClassInstances]]]]
Here is a Playground screen capture.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.