gpt4 book ai didi

ios - UserDefaults 保存字典数组

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

我正在尝试将字典保存到 UserDefaults 中,然后我想获取数据或删除数据。

class userDefaultsManager {

static func getAllUsers()->[UserModel]{

if let all = UserDefaults.standard.array(forKey: "usersKey") as? [Dictionary<String,Any>] {
return all.map{UserModel.init(dictionary: $0)}
}
return []
}

static func insertUser(name:String, email:String)->Bool {

let newUserModel = UserModel.init(name: name, email: email)

var all = getAllUser()
all.append(newUserModel)

UserDefaults.standard.set(all.map{$0.dictionary}, forKey: "usersKey")

return UserDefaults.standard.synchronize()
}

static func deleteUser(email:String)->Bool {

var all = getAllUser()
let index = all.index{$0.email == email}

if index != nil {

all.remove(at: index!)

UserDefaults.standard.set(all.map{$0.dictionary}, forKey: "usersKey")
UserDefaults.standard.synchronize()

return true

} else {
return false
}
}
}

class UserModel:NSObject{

var name: String!
var email: String!

init(name:String, email:String) {

self. name = name
self. email = email

super.init()
}

init(dictionary:[String:Any]) {

self.name = ""
self.email = ""

super.init()
self.setValuesForKeys(dictionary)
}

var dictionary:[String:Any] {
return self.dictionaryWithValues(forKeys: ["name","email"]) //Error here
}
}

代码在 swift 3 上工作,但我在 var dictionary:[String:Any] 上遇到 swift 4 错误

这里是错误:

implicit Objective-C entrypoint -[Myapp.UserModel name] is deprecated and will be removed in Swift 4

如有任何帮助解决此问题,我们将不胜感激。

最佳答案

你的类继承自 NSObject,并使用 objc KVC,这对 Swift3 来说很好,因为 Swift3 默认将所有 NSObject 子类假定为@objc,在 Swift4 中你需要声明你的访问器 @objc 以使它们可用于 obj-c KVC 操作。 https://forums.developer.apple.com/thread/81789

关于ios - UserDefaults 保存字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187955/

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