Reputation: 2274
I recently realized that NSManagedObject subclasses inherit a class method entity
which can be used to obtain a NSEntityDescription
for the class. However, I was used to having to specify a context when creating a NSEntityDescription
, as with entityForName:inManagedObjectContext:
. Is it ok to use the simpler entity
method and what context will it be associated with ?
This method is not really documented by Apple.
Upvotes: 1
Views: 226
Reputation: 70966
An NSEntityDescription
is not part of a managed object context-- it's part of the managed object model.
When you load a data model, all of the entity descriptions it contains are loaded. The class method +entity
works because the entity description was created along with the model object. If you try to call this method before loading the model, it returns nil
in Objective-C. (In Swift for some reason it returns a non-optional value, so it's not nil, but if you use it your app will crash. Don't ask me why it's like this.)
You can also use +entityForName:inManagedObjectContext:
, as you mentioned. But look at the documentation for that method:
Returns the entity with the specified name from the managed object model associated with the specified managed object context’s persistent store coordinator.
So even though the method takes a managed object context argument, it's still using the managed object model. It's using the context to find the model. The object that you get isn't associated with the context, it's associated with the underlying data model.
These two methods are equally safe. Use whichever works best in your code.
Upvotes: 1