我有一个班
class Player { var name = "" func encodeWithCoder(encoder: NSCoder) { encoder.encodeObject(name) } func initWithCoder(decoder: NSCoder) -> Player { self.name = decoder.decodeObjectForKey("name") as String return self } init(coder aDecoder: NSCoder!) { self.name = aDecoder.decodeObjectForKey("name") as String } init(name: String) { self.name = name } }
我想要序列化并保存到用户默认值.
首先我不知道如何正确编写编码器和解码器.所以对于init我写了两个方法.
当我尝试执行这个代码:
func saveUserData() { let player1 = Player(name: "player1") let myEncodedObject = NSKeyedArchiver.archivedDataWithRootObject(player1) NSUserDefaults.standardUserDefaults().setObject(myEncodedObject,forKey: "player") }
应用程式崩溃,我收到这则讯息:
*** NSForwarding: warning: object 0xebf0000 of class '_TtC6GameOn6Player' does not implement methodSignatureForSelector: -- trouble ahead
我做错了什么?
解决方法
NSKeyedArchiver只能使用Objective-C类,而不是纯粹的Swift类.您可以通过使用@objc属性或通过继承自Objective-C类(如NSObject)来将您的类桥接到Objective-C.
有关更多信息,请参阅Using Swift with Cocoa and Objective-C.