问题
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