Created
March 17, 2015 03:41
-
-
Save majie1993/5b5e12c8e21eb7b5c4e0 to your computer and use it in GitHub Desktop.
From http://stackoverflow.com/questions/2239797/core-data-unique-attributes
Unique Item in Core Data
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
+ (TZUser *)userWithUniqueUserId:(NSString *)uniqueUserId inManagedObjectContext:(NSManagedObjectContext *)context | |
{ | |
TZUser *user = nil; | |
NSFetchRequest *request = [[NSFetchRequest alloc] init]; | |
request.entity = [NSEntityDescription entityForName:@"TZUser" inManagedObjectContext:context]; | |
request.predicate = [NSPredicate predicateWithFormat:@"objectId = %@", uniqueUserId]; | |
NSError *executeFetchError = nil; | |
user = [[context executeFetchRequest:request error:&executeFetchError] lastObject]; | |
if (executeFetchError) { | |
NSLog(@"[%@, %@] error looking up user with id: %i with error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), [uniqueUserId intValue], [executeFetchError localizedDescription]); | |
} else if (!user) { | |
user = [NSEntityDescription insertNewObjectForEntityForName:@"TZUser" | |
inManagedObjectContext:context]; | |
} | |
return user; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment