NSManagedObject managedObjectContext property is zero

I am trying to create a temporary context for a managed object, and after several screens of the user entering the information, I combine this context with the main context (so that no "incomplete" objects are inserted). This is how I create my temporary context and how I insert an object into it:

if (!self.someManagedObject) { NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:@[[NSBundle mainBundle]]]; NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; [storeCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:nil]; NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator:storeCoordinator]; self.someManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"SomeObject" inManagedObjectContext:managedObjectContext]; NSLog(@"%@", self.someManagedObject.managedObjectContext); } 

This is part of viewDidLoad . The console shows that the context of the managed entity matters.

However, right after this if statement (even inside viewDidLoad , self.someManagedObject.managedObjectContext is nil. I can understand why the local variable will no longer be available (it just goes out of scope), but the property of the managed object should still be set, right?

I know that I can create a property to hold the context of a managed entity, but I would prefer it to work that way.

+5
iphone core-data nsmanagedobjectcontext
source share
2 answers

I recently ran into the same problem again, although that was in a different situation. I need a temporary context of the managed object, completely separated from the main one, but again I encountered the problem of its disappearance after it went out of scope. This time I decided to continue the research, and eventually I realized that managedObjectContext not a property of NSManagedObject , but a method. This means one of two things:

  • If it uses a property in the base implementation, this property will not contain a reference to in context
  • If the context of the managed object is displayed in some other way, it will also not contain links to this context.

In any case, the context has no strong links, goes beyond the scope, and NSManagedObject has nil managedObjectContext .

The solution was to simply maintain the context by creating a strong property for it.

+15
source share

I don’t understand why you need the second context of the managed entity. IMHO, you enter complexity into your application, which does not serve any specific purpose.

Insert a new object into the main context. Let the user enter their data. If it breaks, just call

 [managedObjectContext rollback]; 

or, if the user finishes and all data is verified, call

 [managedObjectContext save:nil]; 
-2
source share

All Articles