Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an NSManagedObject Without Saving? [duplicate]

Possible Duplicate:
Store But Don't Save NSManagedObject to CoreData?

I need to make an NSManagedObject without saving it, how can I do this?

The reason I want to do this is the app has a setup in which the user enters their details, however I only want to save the object if they complete the setup (they have the option to cancel, in which case the object needs to be discarded without being saved, which is why I don't want to insert it straight away).

I have tried insetting one without a context but the app crashes.

I have tried the following:

GuestInfo *guest;
guest = (GuestInfo *)[NSEntityDescription insertNewObjectForEntityForName:@"GuestInfo" inManagedObjectContext:nil];

This causes the crash with the following error message:

'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'GuestInfo''
like image 414
Josh Kahane Avatar asked Apr 15 '12 22:04

Josh Kahane


2 Answers

I would recommend creating the managed object and inserting into your managed object context as normal. You will have a reference to the managed object, i.e.:

GuestInfo* guest = (GuestInfo *)[NSEntityDescription insertNewObjectForEntityForName:@"GuestInfo" inManagedObjectContext:managedObjectContext];

Then if the user cancels, just delete it from the managed object context like this:

[guest deleteInContext:managedObjectContext];

The managed object context is designed as a scratchpad for you to create and delete objects in it like this.

Another option you might consider is calling:

[managedObjectContext rollback]

if the user cancels. i.e. you would create the managed object in the managed object context, but if the user cancels, you undo or rollback the state of the managed object context to how it was at the last time it was saved. See the "Undo Management" section of the Apple's "Using Managed Objects" doc:

https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/Articles/cdUsingMOs.html

like image 150
Rob B Avatar answered Nov 18 '22 03:11

Rob B


Create a NSManagedObjectContext, as a child of your normal context. You can make all the changes in there that you want, and as long as you don't call save, the stuff in there will not get pushed.

For example...

NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSPrivateQueueConcurrencyType];
moc.parentContext = myCurrentManagedObjectContext;

Now, from within any thread in your program, you can make the following call...

[moc performBlock:^{
    // Do anything you want to with this context... make a new object, whatever.
    // As long as you do not call [moc save], your changes will not propagate
    // up to the parent context, nor saved.
}];
like image 36
Jody Hagins Avatar answered Nov 18 '22 02:11

Jody Hagins