我有自定義類名爲User
的女巫符合NSCoding協議。但是,當我試圖存儲它NSUserDefaults的中我得到這個錯誤:在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)
即使符合NSCoding,您也不能將自定義對象存儲到NSUserDefaults – vivek
@vivek? – rabbitinspace
我還沒有嘗試,但也許你的類必須基於NSObject?因此,類User:NSObject,NSCoding – Volker