Search code examples
iosobjective-ccore-datansmanagedobjectnsmanagedobjectcontext

Creating a memory-only NSManagedObject model


I need to create an instance of a NSManagedObject that will not be saved in CoreData and only in memory.

e.g.:

I have the Item and Log NSManagedObject, and they have relations between them. I want to be able to create a Log instance without any core data properties, and assign its item property to an Item instance.

I know I can create it in a different, memory-persistence, context (or nil context). But then I can't assign the item property, since my Item instance is in the core-data context.

NSEntityDescription *description = [NSEntityDescription entityForName:@"Log" inManagedObjectContext:defaultContext];
Log *log = [[Log alloc] initWithEntity:description insertIntoManagedObjectContext:nil];
log.item = item;

This code throws an exception when ran:

Illegal attempt to establish a relationship 'item' between objects in different contexts

How can I achieve this in another way?


Solution

  • You can create a NSManagedObjectContext with parent context set to your Log's MOC.