在NSUserDefaults中存储自定义对象时,应用程序崩溃

时间:2015-01-16 06:10:37

标签: ios xcode swift

我有一个名为User的自定义类,符合NSCoding协议。但是当我试图将它存储在NSUserDefaults中时,我收到了这个错误:

Property list invalid for format: 200 
(property lists cannot contain objects of type 'CFType')

这个警告:

NSForwarding: warning: object 0x7f816a681110 of class 'Shikimori.User'
does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[Shikimori.User _copyDescription]

User上课:

class User: NSCoding {

private enum CoderKeys: String {
    case ID = "user.id"
    case Username = "user.username"
    case Email = "user.email"
    case Avatar = "user.avatar"
}

let id: Int
let username: String
let email: String
let avatar: String

init(id: Int, username: String, email: String, avatar: String) {
    self.id = id
    self.username = username
    self.email = email
    self.avatar = avatar
}

required init(coder aDecoder: NSCoder) {
    id = aDecoder.decodeIntegerForKey(CoderKeys.ID.rawValue)
    username = aDecoder.decodeObjectForKey(CoderKeys.Username.rawValue) as String
    email = aDecoder.decodeObjectForKey(CoderKeys.Email.rawValue) as String
    avatar = aDecoder.decodeObjectForKey(CoderKeys.Avatar.rawValue) as String
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeInteger(id, forKey: CoderKeys.ID.rawValue)
    aCoder.encodeObject(username as NSString, forKey: CoderKeys.Username.rawValue)
    aCoder.encodeObject(email as NSString, forKey: CoderKeys.Email.rawValue)
    aCoder.encodeObject(avatar as NSString, forKey: CoderKeys.Avatar.rawValue)
}
}

更新 保存代码:

let userKeyForDefaults = "apimanager.user"


let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(user, forKey: self.userKeyForDefaults)

1 个答案:

答案 0 :(得分:4)

NSUserDefaults不支持所有对象,只支持NSStringNSDictionary,最重要的是NSData。这就是NSCoding协议派上用场的地方。它允许我们将自定义对象转换为NSData的块。为此,请使用NSKeyedArchiver类将符合NSCoding的自定义对象转换为等效NSData

let obj = User()
let data = NSKeyedArchiver. archivedDataWithRootObject(obj)
/// Now you can store data

可以找到文档here,您要查找的方法是

class func archivedDataWithRootObject(_ rootObject: AnyObject) -> NSData

要获取NSUserDefaults out ,请使用" inverse" class,NSKeyedUnarchiver。其适用方法如下

class func unarchiveObjectWithData(_ data: NSData) -> AnyObject?

以下是一个示例。

let data = NSUserDefaults.standardUserDefaults().objectForKey("somekey")
let obj = NSKeyedUnarchiver. unarchiveObjectWithData(data) as User?

注意:我可能混淆了一些选项,但你得到了jist。可以找到NSKeyedUnarchiver的文档here

编辑:修复OP的问题就像使用NSKeyedArchiver和继承NSObject一样简单。