Friday 22 May 2015

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.
  1. -(void)parseJsonAndSaveToUserEntity:(NSDictionary*) details{
  2. for (int i=0; i<details.count; i++) {
  3. NSPredicate *predicate = [NSPredicate predicateWithFormat: @"%K == %@", @"user_id", [[[details objectAtIndex:i] valueForKey:@"user_id"]];
  4. NSArray *temp = fetchManagedObjects(@"UserData", predicate, nil, defaultManagedObjectContext());
  5. if (!temp.count<=0){
  6. NSLog(@"Do Nothing if data already exist!");
  7. return;
  8. }else{
  9. UserData *userInfo = [NSEntityDescription
  10. insertNewObjectForEntityForName:@"UserData"
  11. inManagedObjectContext:defaultManagedObjectContext()];
  12. [userInfo setUser_id:[[details objectAtIndex:i] valueForKey:@"user_id"]];
  13. NSError *errors = nil;
  14. if (! [defaultManagedObjectContext() save:&errors]) {
  15. // Uh, oh. An error happened. :(
  16. }
  17. }
  18. }
  19. }
Method to get NSManagedObjectContext. (or use global NSManagedObjectContext)
  1. NSManagedObjectContext *
  2. defaultManagedObjectContext()
  3. {
  4. NSManagedObjectContext *moc = nil;
  5. id appDelegate = [[UIApplication sharedApplication] delegate];
  6. if ([appDelegate respondsToSelector:@selector(managedObjectContext)]) {
  7. moc = [appDelegate managedObjectContext];
  8. }
  9. return moc;
  10. }
Method to apply unique key Predicate.
  1. NSArray *
  2. fetchManagedObjects(NSString *entityName, NSPredicate *predicate, NSArray *sortDescriptors, NSManagedObjectContext *moc)
  3. {
  4. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  5. [fetchRequest setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:moc]];
  6. // Add a sort descriptor. Mandatory.
  7. [fetchRequest setSortDescriptors:sortDescriptors];
  8. fetchRequest.predicate = predicate;
  9. NSError *error;
  10. NSArray *fetchResults = [moc executeFetchRequest:fetchRequest error:&error];
  11. if (fetchResults == nil) {
  12. // Handle the error.
  13. NSLog(@"executeFetchRequest failed with error: %@", [error localizedDescription]);
  14. }
  15. return fetchResults;
  16. }

For such more Blogs you can visit to http://findnerd.com/NerdDigest

No comments:

Post a Comment