Skip to content

Instantly share code, notes, and snippets.

@indragiek
Created October 22, 2013 00:53
Show Gist options
  • Save indragiek/7093508 to your computer and use it in GitHub Desktop.
Save indragiek/7093508 to your computer and use it in GitHub Desktop.
Puzzling Core Data crasher
- (id)insertObjectOfEntityName:(NSString *)entityName configure:(void(^)(id))block
{
NSAssert([NSThread isMainThread], @"Wrong thread bro");
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:self.mainQueueContext];
if (block) block(object);
NSError *error = nil;
if (![self.mainQueueContext save:&error]) {
NSLog(@"Error saving MOC: %@", error);
}
return object;
}
- (void)someMethod
{
[self insertObjectOfEntityName:@"Something" configure:^(Something *obj) {
// managedObjectContext is nil at this point, which causes things to go very very wrong with the
// rest of the code in this block...
NSLog(@"%@", obj.managedObjectContext);
}];
}
@indragiek
Copy link
Author

That's what I'm trying right now (don't have enough info to report back on whether that worked) but it was a shot in the dark and I'm still confused as to what's actually going on. mainQueueContext is confirmed to not be nil, and a strong reference is held for the lifetime of the app.

EDIT: I should also mention that this actually works properly 99% of the time, but it does crash once every now and then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment