Created
July 12, 2013 15:57
-
-
Save blork/5985523 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| + (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]; | |
| }]; | |
| } |
Actually you should use valueForKeyPath: for KVC.
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
Rather than
Could you not do