Skip to content

Instantly share code, notes, and snippets.

@tapoton
Last active December 7, 2015 16:47
Show Gist options
  • Save tapoton/8823a9ff5fd05fdc0fb3 to your computer and use it in GitHub Desktop.
Save tapoton/8823a9ff5fd05fdc0fb3 to your computer and use it in GitHub Desktop.
Fast CoreData parsing helper method (uses MagicalRecord 2.x)
/**
* returns the dictionary of updated or created managed objects where the key is object's entityIdentifierKey value
* requires identifier to be unique
* parsingBlock needs to implement the updating of each object from with assosiated dictionary
*/
+ (NSDictionary *)parseObjectsForClass:(Class)objectClass
fromArray:(NSArray *)array
entityIdentifierKey:(NSString *)entityIdentifierKey
dictIdentifierKey:(NSString *)dictIdentifierKey
deleteUnmatched:(BOOL)deleteUnmatched
inContext:(NSManagedObjectContext *)context
parsingBlock:(void(^)(id object, BOOL isCreated, NSDictionary *dict))parsingBlock {
NSArray *existingObjects = [[objectClass class] MR_findAllInContext:context];
NSArray *existingIdentifiers = [existingObjects valueForKey:entityIdentifierKey];
NSMutableDictionary *existingObjectsByID = [NSMutableDictionary dictionaryWithObjects:existingObjects
forKeys:existingIdentifiers];
NSMutableDictionary *parsedObjects = [NSMutableDictionary dictionaryWithCapacity:array.count];
for (NSDictionary *dict in array) {
NSNumber *identifier = dict[dictIdentifierKey];
if ([identifier isEqual:[NSNull null]]) {
continue;
}
id object = existingObjectsByID[identifier];
BOOL created = NO;
if (object) {
[existingObjectsByID removeObjectForKey:identifier];
} else {
created = YES;
object = [[objectClass class] MR_createInContext:context];
[object setValue:identifier forKey:entityIdentifierKey];
}
if (parsingBlock) {
parsingBlock(object, created, dict);
}
parsedObjects[identifier] = object;
}
if (deleteUnmatched) {
for (id objectToDelete in existingObjectsByID.allValues) {
[objectToDelete MR_deleteInContext:context];
}
}
return parsedObjects;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment