I'm trying to create a temporary managed object context, and after a few screens of the user putting in information, I merge that context with the main context (to ensure that there are no "incomplete" objects are inserted). This is how I create my temporary context and how I insert an object in 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 a part ofviewDidLoad
. In the console it shows that managed object context has a value.
However, right after this if statement (even within viewDidLoad
, self.someManagedObject.managedObjectContext
is nil. I can see why the local variable would not be available anymore (it simply goes out of scope), but the managed object's property should still be set, right?
I know I can create a property to store the managed object context, but I'd rather get it to work this way.
I recently ran into the same problem again, although it was in a different situation. I needed a temporary managed object context, completely separate from the main one, but I again ran into the problem of it disappearing after it goes out of scope. This time I decided to investigate further, and I ultimately realized that managedObjectContext
is not a property of NSManagedObject
, but a method. This means one of two things:
In either case, the context has no strong references, goes out of scope, and the NSManagedObject
s have a nil
managedObjectContext
.
The solution was to simply keep the context around by creating a strong property for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With