Unique Key in Core data
There is no such method to create an unique Key attribute in core data Entity. But we can insert data into entities on the basis of an unique json or XML data object.
Here is an example:-
While parsing API Json Data write the below code inside the loop.
Method to get NSManagedObjectContext. (or use global NSManagedObjectContext)
Method to apply unique key Predicate.
For such more Blogs you can visit to http://findnerd.com/NerdDigest
Here is an example:-
While parsing API Json Data write the below code inside the loop.
- -(void)parseJsonAndSaveToUserEntity:(NSDictionary*) details{
- for (int i=0; i<details.count; i++) {
- NSPredicate *predicate = [NSPredicate predicateWithFormat: @"%K == %@", @"user_id", [[[details objectAtIndex:i] valueForKey:@"user_id"]];
- NSArray *temp = fetchManagedObjects(@"UserData", predicate, nil, defaultManagedObjectContext());
- if (!temp.count<=0){
- NSLog(@"Do Nothing if data already exist!");
- return;
- }else{
- UserData *userInfo = [NSEntityDescription
- insertNewObjectForEntityForName:@"UserData"
- inManagedObjectContext:defaultManagedObjectContext()];
- [userInfo setUser_id:[[details objectAtIndex:i] valueForKey:@"user_id"]];
- NSError *errors = nil;
- if (! [defaultManagedObjectContext() save:&errors]) {
- // Uh, oh. An error happened. :(
- }
- }
- }
- }
Method to get NSManagedObjectContext. (or use global NSManagedObjectContext)
- NSManagedObjectContext *
- defaultManagedObjectContext()
- {
- NSManagedObjectContext *moc = nil;
- id appDelegate = [[UIApplication sharedApplication] delegate];
- if ([appDelegate respondsToSelector:@selector(managedObjectContext)]) {
- moc = [appDelegate managedObjectContext];
- }
- return moc;
- }
Method to apply unique key Predicate.
- NSArray *
- fetchManagedObjects(NSString *entityName, NSPredicate *predicate, NSArray *sortDescriptors, NSManagedObjectContext *moc)
- {
- NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
- [fetchRequest setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:moc]];
- // Add a sort descriptor. Mandatory.
- [fetchRequest setSortDescriptors:sortDescriptors];
- fetchRequest.predicate = predicate;
- NSError *error;
- NSArray *fetchResults = [moc executeFetchRequest:fetchRequest error:&error];
- if (fetchResults == nil) {
- // Handle the error.
- NSLog(@"executeFetchRequest failed with error: %@", [error localizedDescription]);
- }
- return fetchResults;
- }
For such more Blogs you can visit to http://findnerd.com/NerdDigest