Search code examples
iosswiftcore-datakvc

Core Data setValue for Multiple Attributes at once


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 ?


Solution

  • 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)