Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 8 – Creating temporary NSManagedObjects

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.

like image 402
Janum Trivedi Avatar asked Aug 20 '14 14:08

Janum Trivedi


1 Answers

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

like image 59
Daij-Djan Avatar answered Sep 20 '22 15:09

Daij-Djan