Skip to content

Instantly share code, notes, and snippets.

@blork
Created July 12, 2013 15:57
Show Gist options
  • Select an option

  • Save blork/5985523 to your computer and use it in GitHub Desktop.

Select an option

Save blork/5985523 to your computer and use it in GitHub Desktop.
+ (void) insertOrUpdate:(NSArray*)dictArray
forUniqueKey:(NSString*)key
withBlock:(void (^) (NSDictionary* dictionary, NSManagedObject* object))block
inStore:(Store *) store
error:(NSError*)error
{
NSManagedObjectContext* context = [store privateContext];
__block NSError *localError = nil;
[context performBlockAndWait:^{
NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
NSArray* sortedResponse = [dictArray sortedArrayUsingDescriptors:@[sortDescriptor]];
NSArray* fetchedValues = [sortedResponse valueForKeyPath:key];
// Create the fetch request to get all objects matching the unique key.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[self entityWithContext:context]];
[fetchRequest setPredicate: [NSPredicate predicateWithFormat:@"(%K IN %@)", key, fetchedValues]];
[fetchRequest setSortDescriptors: @[sortDescriptor]];
NSArray *objectsMatchingKey = [context executeFetchRequest:fetchRequest error:&localError];
if (localError) {
return;
}
NSEnumerator* objectEnumerator = [objectsMatchingKey objectEnumerator];
NSEnumerator* dictionaryEnumerator = [sortedResponse objectEnumerator];
NSDictionary* dictionary;
id object = [objectEnumerator nextObject];
SEL selector = NSSelectorFromString(key);
while (dictionary = [dictionaryEnumerator nextObject]) {
if (object != nil && [[object performSelector:selector] isEqualToString:dictionary[key]]) {
if (block) {
block(dictionary, object);
}
object = [objectEnumerator nextObject];
} else {
id newObject = [object insertInContext:context];
if (block) {
block(dictionary, newObject);
}
}
}
[context save:nil];
}];
}
@lukestringer90
Copy link

Rather than

SEL selector = NSSelectorFromString(key);
[[object performSelector:selector] isEqualToString:dictionary[key]]

Could you not do

[[object valueForKey:key] isEqualToString:dictionary[key]]

@lukestringer90
Copy link

Actually you should use valueForKeyPath: for KVC.

@lukestringer90
Copy link

Actually you should use valueForKeyPath: for KVC.

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