在NSUserDefaults中保存类的奇怪问题

时间:2016-10-30 23:10:41

标签: ios swift nsuserdefaults

我有下一堂课:

class UnreadMessages: NSObject {
let publicID: String
let messagesCount: Int

init(publicID: String, messagesCount: Int) {
    self.publicID = publicID
    self.messagesCount = messagesCount
}

required init(coder aDecoder: NSCoder) {
    self.publicID = aDecoder.decodeObjectForKey("publicID") as! String
    self.messagesCount = aDecoder.decodeObjectForKey("messagesCount") as! Int
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(publicID, forKey: "publicID")
    aCoder.encodeObject(messagesCount, forKey: "messagesCount")
}
}

我将它保存在NSUserDefault中:

var chatList = [UnreadMessages]()
NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(chatList), forKey: "ChatList")

然后我尝试将这些值设为:

if let data = NSUserDefaults.standardUserDefaults().objectForKey("ChatList") as? NSData {
        let blog = NSKeyedUnarchiver.unarchiveObjectWithData(data)
        print(blog)
    }

但是当我尝试打印blog.publicID时,它会给我下一个错误:

error: <EXPR>:2:10: error: 'UnreadMessages' is ambiguous for type lookup in this context blog as! UnreadMessages

我该如何解决?

0 个答案:

没有答案