Janum Trivedi
Janum Trivedi

Reputation: 1690

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.

Upvotes: 5

Views: 1760

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50099

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

Upvotes: 5

Related Questions