Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 18th, 2012  |  syntax: None  |  size: 1.68 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. iOS Core Data how to properly compare string text using predicates?
  2. -(BOOL)uniqueEntityExistsWithEnityName:(NSString*)entityName UniqueKey:(NSString*) uniqueKey UniqueValue:(NSString*)uniqueValue SortAttribute:(NSString*)sortDescriptorAttribute ManagedObjectContext:(NSManagedObjectContext*) context;
  3. {
  4.     BOOL returnValue = NO;
  5.  
  6.     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
  7.  
  8. //what is the correct predates to compare the text an string core data property against a passed in string?
  9.     request.predicate = [NSPredicate predicateWithFormat:@"unique= %@", uniqueValue];
  10.  
  11.     NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:sortDescriptorAttribute ascending:YES];
  12.     request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];  
  13.  
  14.     NSError *error = nil;
  15.     NSArray *matches = [context executeFetchRequest:request error:&error];
  16.     if (!matches)
  17.     {
  18.          NSLog(@"Error: no object matches");
  19.     }
  20.     else if([matches count] > 1) {
  21.         NSLog(@"Error: More than one object for unique record");
  22.         returnValue = YES;
  23.  
  24.     } else if ([matches count] == 0) {
  25.         returnValue = NO;
  26.     } else {
  27.         returnValue = YES;
  28.     }
  29.  
  30.     return returnValue;
  31. }
  32.        
  33. [NSPredicate predicateWithFormat:@"unique LIKE %@", uniqueValue];
  34.        
  35. if (!matches)
  36. {
  37.     NSLog(@"Error: couldn't execute fetch request %@", error);
  38. }
  39. else if([matches count] > 1) {
  40.     NSLog(@"Error: More than one object for unique record");
  41.     returnValue = YES;
  42. } else if ([matches count] == 0) {
  43.     NSLog(@"couldn't match objects");
  44.     returnValue = NO;
  45. } else {
  46.     // [matches count] == 1
  47.     NSLog(@"matched one object");
  48.     returnValue = YES;
  49. }