【问题标题】:Send Dictionary to Core Data将字典发送到核心数据
【发布时间】:2017-07-14 04:17:24
【问题描述】:

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

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 as? String 作为每个 CoreData 属性的值。

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

这是我的数据模型:

【问题讨论】:

    标签: ios swift xcode firebase core-data


    【解决方案1】:

    您应该能够通过 Core Data 自省来做到这一点。你会做这样的事情:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      相关资源
      最近更新 更多