UserDefaults Bool FAIL

时间:2017-11-13 05:59:04

标签: ios swift nsuserdefaults

我正在尝试使用UserDefaults保存以下数据,但是当我通过isDefault bool时,它不起作用。但如果我删除isDefault,它就可以正常工作。

https://gist.github.com/n1tesh/4de0fea9514e392e35e241786f51e98b

struct User {

    var userContact  = CNContact()
    var recipientContact: CNContact?
    var isDefault: Bool = false
    init(userContact: CNContact, recipientContact: CNContact? = nil, isDefault: Bool) {
        self.userContact = userContact
        self.recipientContact = recipientContact
        self.isDefault = isDefault
    }

}

extension User {
    @objc(_TtCV6testUD4User6Coding)class Coding: NSObject, NSCoding {

        let model: User?

        init(model: User) {
            self.model = model
            super.init()
        }

        func encode(with aCoder: NSCoder) {
            guard let model = self.model else {
                return
            }

            aCoder.encode(model.userContact, forKey: "userContact")
            aCoder.encode(model.recipientContact, forKey: "recipientContact")
            aCoder.encode(model.isDefault, forKey: "isDefault")

        }

        required init?(coder aDecoder: NSCoder) {
            guard let userContact = aDecoder.decodeObject(forKey: "userContact") as? CNContact,let isDefault = aDecoder.decodeObject(forKey: "isDefault") as? Bool  else  {
                    return nil
            }
          let recipientContact = aDecoder.decodeObject(forKey: "recipientContact") as? CNContact

            model = User(userContact: userContact, recipientContact: recipientContact, isDefault: isDefault)
            super.init()
        }

    }
}

1 个答案:

答案 0 :(得分:2)

NSCoding Bool而言,不是一个对象。使用专用方法decodeBool(forKey

let isDefault = aDecoder.decodeBool(forKey: "isDefault")

结果是非可选的Bool