gpt4 book ai didi

ios - 将字典发送到核心数据

转载 作者:搜寻专家 更新时间:2023-11-01 07:10:44 31 4
gpt4 key购买 nike

我有一个键值对字典,我正试图将其保存到核心数据中。

let children = userSnap.children.allObjects as! [DataSnapshot]
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let thisUser = ThisUser(context: context)
var data = [String: String]()
for child in children {
data[child.key] = child.value as? String
}
data["uid"] = currentUser!.uid

child.key 字符串与 CoreData 中的属性匹配,我想将 child.value 设置为? String 作为每个 CoreData 属性的值。

有没有一种方法可以做到这一点而不必为每个属性创建一行代码...例如)thisUser.uid = data["uid]

这是我的数据模型:

enter image description here

最佳答案

您应该能够通过核心数据内省(introspection)来做到这一点。你会做类似的事情:

  • 获取 NSEntityDescription 作为 thisUser.entity
  • 通过在实体描述上调用 attributesByName 来获取 [String: NSAttributeDescription] 的字典,从而获取实体中的属性列表。
  • 该字典的键是您的 Core Data 属性的名称。使用该键从字典中获取值。使用键值编码为您的托管对象赋值,即 setValue(_:, forKey:)
  • 如有必要,您还可以使用 attributesByName 的结果来找出属性的类型。使用 NSAttributeDescriptionattributeType 属性。

基本上,找出您的 Core Data 对象具有哪些属性,获取它们的名称,然后遍历这些名称以将数据从一个地方复制到另一个地方。

关于ios - 将字典发送到核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45089340/

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