Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create an new instance of my custom managed object class without going through NSEntityDescription?

From an Apple example, I have this:

Event *event = (Event*)[NSEntityDescription 
    insertNewObjectForEntityForName:@"Event" 
             inManagedObjectContext:self.managedObjectContext];

Event inherits from NSManagedObject. Is there a way to avoid this weird call to NSEntityDescription and instead just alloc+init somehow directly the Event class? Would I have to write my own initializer that just does that stuff above? Or is NSManagedObject already intelligent enough to do that?

like image 679
openfrog Avatar asked Jan 25 '10 15:01

openfrog


2 Answers

NSManagedObject provides a method called initWithEntity:insertIntoManagedObjectContext:. You can use this to do a more traditional alloc/init pair. Keep in mind that the object this returns is not autoreleased.

like image 198
Alex Avatar answered Oct 22 '22 20:10

Alex


I've run into the exact same problem. It turns out you can completely create an entity and not add it to the store at first, then make some checks on it and if everything is good insert it into the store. I use it during an XML parsing session where I only want to insert entities once they have been properly and entirely parsed.

First you need to create the entity:

// This line creates the proper description using the managed context and entity name. 
// Note that it uses the managed object context
NSEntityDescription *ent = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:[self managedContext]];

// This line initialized the entity but does not insert it into the managed object context.    
currentEntity = [[Location alloc] initWithEntity:ent insertIntoManagedObjectContext:nil];

Then once you are happy with the processing you can simply insert your entity into the store:

[self managedContext] insertObject:currentEntity

Note that in those examples the currentEntity object has been defined in a header file as follows:

id currentEntity
like image 43
MiKL Avatar answered Oct 22 '22 19:10

MiKL