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!

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182
Kerman
  • 1
  • 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 '14 at 06:12
  • Alright, so is it okay to pass managedobjects and contexts across view controllers – Kerman Feb 15 '14 at 07: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 '14 at 09:51

0 Answers0