0

I'm using Magical Record to manage Core Data in my app which uses Kinvey. On my NSManagedObject I've implemented the following method as a requirement for Kinvey's SDK to work with Core Data.

+ (id)kinveyDesignatedInitializer:(NSDictionary *)jsonDocument
{
NSString* existingID = jsonDocument[KCSEntityKeyId];

Task* obj = nil;
NSManagedObjectContext* context = [NSManagedObjectContext MR_defaultContext];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Task" inManagedObjectContext:context];
if (existingID) {
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"kinvey_id = %@", existingID];
    [request setPredicate:predicate];
    NSArray* results = [context executeFetchRequest:request error:NULL];
    if (results != nil && results.count > 0) {
        obj = results[0];
    }
}
if (obj == nil) {
    //fall back to creating a new if one if there is an error, or if it is new
    obj = [[self alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
}

return obj;
}

However I'm not sure if this is the correct way of obtaining the context for the NSManagedObject.

NSManagedObjectContext* context = [NSManagedObjectContext MR_defaultContext];

Also I'm extremely confused on handling my NSManagedObjectContexts and NSManagedObjects

In one of my current apps I've set my structure as this:

Main App View Controller 
- self.editingContext = [NSManagedObjectContext MR_defaultContext];

Detail Object Views
- self.editingContext = [NSManagedObjectContext MR_contextForCurrentThread];
- self.currentObject = [self.editingContext objectWithID:objectID]; (objectID passed from MAVC)

I'm getting reports of the app crashing, so something's obviously not right. For the new app I was thinking to have the following structure but I'm not sure if it's okay to pass managedobjects and contexts across view controllers.

Main App View Controller
- self.editingContext = [NSManagedObjectContext MR_defaultContext];
- detailVC.currentObject = managedObject;

Detail Object Views
- self.editingContext = self.currentObject.managedObjectContext;

Any help would be really appreciated!

3
  • First things first, stop using contextForCurrentThead. It will lead to random crashes over time when used with gcd. Simple create a new context for every new background operation.
    – casademora
    Feb 15, 2014 at 6:12
  • Alright, so is it okay to pass managedobjects and contexts across view controllers
    – Kerman
    Feb 15, 2014 at 7:42
  • You can pass them along, but you'll have to be careful to not cross thread boundaries. I generally recommend simply creating new contexts whenever you need them.
    – casademora
    Feb 15, 2014 at 9:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.