Difference between NSEntityDescription creation methods

1.2k Views Asked by At

What is the difference, in terms of outcome, between the 2 following methods:

+ (id)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context;

+ (NSEntityDescription *)entityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context;

When should I use each one of them?

3

There are 3 best solutions below

0
On

insertNewObjectForEntityForName creates an instance of the entity and adds it to the context. The context is now dirty and needs to be saved. The returned instance is a subclass of NSManagedObject.

entityForName returns the NSEntityDescription instance which describes the entity, what attributes and relationships it has, how they are constructed. The context is not modified in any way.

0
On

insertNewObjectForEntityForName:... returns NSManangedObject object which is same as below code.

NSManagedObjectModel *managedObjectModel =
        [[context persistentStoreCoordinator] managedObjectModel];
NSEntityDescription *entity =
        [[managedObjectModel entitiesByName] objectForKey:entityName];
NSManagedObject *newObject = [[NSManagedObject alloc]
            initWithEntity:entity insertIntoManagedObjectContext:context];
return newObject;

entityForName:.. returns NSEntityDescription object which is same as below code.

NSManagedObjectModel *managedObjectModel = [[context persistentStoreCoordinator] managedObjectModel]; 
NSEntityDescription *entity = [[managedObjectModel entitiesByName] objectForKey:entityName]; 
return entity;
0
On

The id variable is a data type that represents an object’s address. Because it’s just an address, id can be any object, and because its type is a pointer,you don’t need to include the * symbol

+ (id)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context;

As the * symbol signifies a pointer to a specific type.

+ (NSEntityDescription *)entityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context;