gpt4 book ai didi

ios - UserDefaults bool 失败

转载 作者:行者123 更新时间:2023-11-28 12:14:27 25 4
gpt4 key购买 nike

我正在尝试使用 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()
}

}
}

最佳答案

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

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

结果是一个非可选的Bool

关于ios - UserDefaults bool 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com