使用NSObject和NSCode我似乎无法取消归档我班级的多个成员。这个类看起来像这样: 进口基金会 import os.log
class myObject:NSObject,NSCoding {
var type:String
var color:String = "White"
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory,in: .userDomainMask).first!
static let ArchiveURL =DocumentsDirectory.appendingPath("myObjects")
struct PropertyKey {
static let type = "type"
static let color = "color"
}
init(objType:String) {
self.type = objType)
}
func encode(with aCoder:NSCoder) {
aCoder.encode(type,forKey:PropertyKey.type)
aCoder.encode(color,forKey:PropertyKey.color)
}
required convenience init?(coder aDecoder: NSCoder) {
print("LOADING object")
guard let myType = (aDecoder.decodeObject(forKey: PropertyKey.type) as? String?)!
else {
os_log("!!! object class unable to decode type.",log:OSLog.default,type: .debug)
return nil
}
self.init(objType: myType)
color = aDecoder.decodeObject(forKey: PropertyKey.color) as! String
}
我有一个ViewController,其viewDidLoad看起来像:
override func viewDidLoad() {
super.viewDidLoad()
let thisObject = loadObject()
print("My object has type: \(String(describing: thisObject?.type))")
print("My object has color: \(String(describing: thisObject?.color))")
}
private func loadObject() -> myObject? {
print("TRYING to LOAD")
return (NSKeyedUnarchiver.unarchiveObject(withFile: myObject.ArchiveURL.path) as? myObject)
}
我得到的输出是 试着加载 我的对象有类型:theTypeIgave 我的对象有颜色:白色
有两件事让我觉得奇怪。 1.当我运行并保存不同类型时,我可以获得不同的类型,但即使我上次运行程序时保存了蓝色或红色,颜色也始终为白色。 2.我从来没有得到print语句在所需的方便init中输出任何东西?函数,那init会被调用吗?