Core Data setValue for Multiple Attributes at once

浪尽此生 提交于 2019-12-09 14:14:26

问题


I have a Book entity in Core Data and a Book class acting as the model layer.

My Book model has multiple attributes. When comes the time to persist the books in Core Data, I would like to store them without having to do

bookObject.setValue(book.title , forKey: "name")
bookObject.setValue(book.author , forKey: "author")
bookObject.setValue(book.datePublished , forKey: "datePublished")
etc...

Is there a method akin to setValue for setting multiple CoreData Entity attributes at once ?


回答1:


If the Book model class inherits from NSObject and uses the same property names and types as the Core Data entity then you can use Key-Value Coding:

let keys = ["title", "author", "datePublished"]
let dict = book.dictionaryWithValuesForKeys(keys)
bookObject.setValuesForKeysWithDictionary(dict)


来源:https://stackoverflow.com/questions/33422180/core-data-setvalue-for-multiple-attributes-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!