Is there a way to instantiate a NSManagedObject without inserting it?

Edward Ashak picture Edward Ashak · Oct 6, 2010 · Viewed 30.4k times · Source

I have a user interface to insert a Transaction. once the user clicks on a plus he gets the screen and i want to instantiate my Core Data NSManagedObject entity let the user work on it. Then when the user clicks on the Save button i will call the save function.

so down to code:

transaction = (Transaction *)[NSEntityDescription insertNewObjectForEntityForName:@"Transaction" inManagedObjectContext:self.managedObjectContext];
//even if i dont call save: its going to show up on my table
[self.managedObjectContext save:&error]

P.S i am using an NSFetchedResultsController on that table and I see that the NSFetchedResultsController is inserting a section and an object to the table.

My thought is if there is a way to instantiate the Transaction NSManagedObject i could update it with out saving untill the client choses to.

Answer

James Huddleston picture James Huddleston · Oct 6, 2010

For what it's worth, Marcus Zarra seems to be promoting the nil context approach, claiming that it's expensive to create a new context. For more details, see this answer to a similar question.

Update

I'm currently using the nil context approach and have encountered something that might be of interest to others. To create a managed object without a context, you use the initWithEntity:insertIntoManagedObjectContext: method of NSManagedObject. According to Apple's documentation for this method:

If context is not nil, this method invokes [context insertObject:self] (which causes awakeFromInsert to be invoked).

The implication here is important. Using a nil context when creating a managed object will prevent insertObject: from being called and therefore prevent awakeFromInsert from being called. Consequently, any object initialization or setting of default property values done in awakeFromInsert will not happen automatically when using a nil context.

Bottom line: When using a managed object without a context, awakeFromInsert will not be called automatically and you may need extra code to compensate.