Reputation: 3628
I am trying to insert into CoreData without creating a subclass of NSManagedObject. but my app crashes with NSManagedObject setValue:forUndefinedKey "name" in Category.
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let entitiyDesc = NSEntityDescription()
entitiyDesc.name = "Category"
guard let data = model.data else { return }
for d in data {
let managedObject = NSManagedObject.init(entity: entitiyDesc, insertIntoManagedObjectContext: managedObjectContext)
managedObject.setValue(d.name, forKey: "name")
}
try! managedObjectContext.save()
What are the benefits of subclassing NSManagedObjects
Upvotes: 2
Views: 997
Reputation: 17500
Marcus Zarra's answer is 100% correct, but I would just like to stress that considering the risks of "undefined key" and type-casting errors, and the debugging cost while mentally remembering which entities have which attribute keys, to subclass or not should not even be a choice.
Strongly-typing your NSManagedObject
s (i.e. by subclassing) also opens up a whole lot of compile-time checks and utility, especially in Swift.
If you are new to Core Data let me introduce you to the library I wrote, CoreStore, which was heavily designed around Swift's type-safety:
NSFetchedResultsController
-like observersYou also get powerful features such as transactions, progressive migrations, and more. It's like Core Data on training wheels; if there's a bad practice in Core Data, CoreStore will most likely not let you write that code in the first place.
Upvotes: 1
Reputation: 46728
There is nothing wrong with the way you are using Core Data. Generally you start wanting to subclass when:
NSManagedObject
NSManagedObject
and I am sure there are more in that list.
You never need to subclass an NSManagedObject
but in many situations it does make your code cleaner and easier to maintain.
A couple of comments on your code:
NSEntityDescription
and NSManagedObject
should not be created that way. You should be using the convenience method NSEntityDescription.insertNewObjectForEntityForName(_:)
insteadNSManagedObjectContext
through the AppDelegate
like that is a poor design (yes I know its in the Apple template). It is far better to use dependency injection as discussed in the Core Data Programming Guide and avoid the tight coupling that is inherent with accessing the AppDelegate
Upvotes: 14
Reputation: 1036
Subclassing NSManagedObject honestly makes your life easier as a developer.
setValue:forUndefinedKey
.You should check out the official documentation or this tutorial to get started.
Upvotes: 1