Search code examples
iosobjective-ccore-datansmanagedobjectcontextmagicalrecord

Saving Context At a Later Stage - Saving Pointer To Context ? Core Data


I have the following code which inserts a new entity into a Core Data model (via Magical Record) :

- (void)insertWithData:(NSDictionary *)dataDictionary {

DLog(@"Inserting %@", [_entityClass description]);

NSManagedObjectContext *context = [NSManagedObjectContext contextForCurrentThread];

id entity = [_entityClass createInContext:context];

[entity setValuesFromDictionary:dataDictionary];

if ([entity isKindOfClass:[Syncable class]]) {
    [entity setValue:YesNumber forKey:@"syncedToServer"];
}

[context save];
}

As this code runs multiple times in a FOR loop called from another class, I would like to only save the context once the loop has completed to optimise performance.

My question is what is the best way to do this ? Should I save a reference to the context here (e.g in the app delegate) and then save using this reference in the calling class ? Or can I just call NSManagedObjectContext contextForCurrent Thread again in the calling class and use this reference - i.e in the calling class :

NSManagedObjectContext * context = [NSManagedObjectContext contextForCurrentThread];
[context save];

Solution

  • Yes, you can save context after loop. It's much better than save in each iteration. If you'll take a look into MagicalRecord src, you'll see that MR_contextForCurrentThread returns always same context for same threads, if there's no context for thread MagicalRecord creates it.
    Also, you don't need to pass context [_entityClass createInContext:context], just [_entityClass MR_createEntity] - it will be created on current thread's context