5

In iOS 7 (and earlier), there was the ability to effectively create "temporary" NSManagedObjects with the option to later add it to a context and persist it, like so:

NSEntityDescription* entityDescription = [NSEntityDescription entityForName:@"User" inManagedObjectContext:managedObjectContext];
User* user = [[User alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];

Note the nil NSManagedObjectContext parameter. (Check out Marcus S. Zarra's answer on this method here)

However, iOS 8 has changed how relationships are managed, such that if you create a temporary object and add a relationship to it before setting its context, the relationship will be deleted upon relaunch:

User* user = [User temporaryEntity];
[user addPhotosObject:photo];
[managedObjectContext:insertObject:user];
[managedObjectContext:&error]; 

This doesn't affect non-relational objects, but does make it impossible to create temporary objects that do have relationships.

Does anyone know how to account for this change and create/use temporary, working NSManagedObjects? Thanks!

--

Also, check out this relevant post on the iOS 8 forum.

Community
  • 1
  • 1
Janum Trivedi
  • 1,660
  • 2
  • 16
  • 24
  • An NSManagedObject is observed by an NSManagedObjectContext - that is where the "management" happens. Attempting to create an NSManagedObject without an NSManagedObjectContext will result in undefined behavior. It's not clear from your question why you want to do this, especially as ALL NSManagedObjects are temporary until they are saved. – quellish Aug 21 '14 at 08:37

1 Answers1

5

create your temp objects in a temp context and also fetch your relationships into that temp context

use the MOC as a 'scratch pad' and save it or don't save the context at the end

thats what I have been doing forever

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • As in a parent-child context? If I created a new object in the temporary context, added relationships to the object, then saved that context, would both the object and its relationships be saved into the parent? Do you mind adding an example? – Janum Trivedi Aug 20 '14 at 15:04
  • 1
    I think you mean MOC (managed object context) rather than MOM (managed object model). You are absolutely correct that the context is intended to be used as a scratch pad - the documentation is quite clear on this. – quellish Aug 21 '14 at 08:38