Skip to content

Instantly share code, notes, and snippets.

@willbailey
Created April 1, 2010 00:34
Show Gist options
  • Save willbailey/351146 to your computer and use it in GitHub Desktop.
Save willbailey/351146 to your computer and use it in GitHub Desktop.
#import "SFFlow.h"
@implementation SFFlow
// Custom logic goes here.
#pragma mark common managed object methods
+ (id *)upsert:(NSDictionary *)data
{
NSEntityDescription *entityDescription = [[self class] entityInManagedObjectContext:[[self class] _moc]];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id = %@", [data objectForKey:@"id"]];
NSError *error;
[request setPredicate:predicate];
NSArray *array = [[[self class] _moc] executeFetchRequest:request error:&error];
if ([array count] == 1) {
id *instance = [array objectAtIndex:0];
[instance populateFromDictionary:data];
} else {
id *instance = [[self class] insertInManagedObjectContext:[[self class] _moc]];
[instance populateFromDictionary:data];
}
if (![[[self class] _moc] save:&error]){
// handle error
};
}
- (id *)populateFromDictionary:(NSDictionary *)data{
for (id key in data) {
NSString* methodName = [NSString stringWithFormat:@"set%@:", [key stringByCapitalizingFirstCharacter]];
if ([self respondsToSelector:NSSelectorFromString(methodName)]) {
if ([key isEqualToString:@"updated_at"] || [key isEqualToString:@"created_at"]) {
NSDate *date = [NSDate dateWithString:[data objectForKey:key]];
[self performSelector:NSSelectorFromString(methodName) withObject:date];
} else {
[self performSelector:NSSelectorFromString(methodName) withObject:[data objectForKey:key]];
}
}
}
}
+ (NSManagedObjectContext *)_moc
{
return [[[UIApplication sharedApplication] delegate] managedObjectContext];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment