Reputation: 441
I am trying to execute a fetch request on NSManagedObjectContenxt and I want the predicate to be case insensitive.
I tried several solutions that I found but all of them works only on NSArray (filteredArrayUsingPredicate) but not on Core Data.
For example:
My persistent store contains an NSManagedObject, 'Car', with the attribute 'name' and its value is "GMC".
1) The following returns with an empty array:
NSFetchRequest* fetch = [[NSFetchRequest alloc] init];
fetch.entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:moc];
fetch.predicate = [NSPredicate predicateWithFormat:@"name matches[c] %@", @"gmc"];
NSArray* cars = [moc executeFetchRequest:fetch error:nil];
2) The following crashes with 'EXC_BAD_ACCESS':
fetch.predicate = [NSPredicate predicateWithFormat:@"name ==[c] %@", @"gmc"];
NSArray* cars = [moc executeFetchRequest:fetch error:nil];
3) The only fetch that works is:
fetch.predicate = [NSPredicate predicateWithFormat:@"name == %@", @"GMC"];
NSArray* cars = [moc executeFetchRequest:fetch error:nil];
Is it possible to do case insensitive fetch in Core Data? And how?
Thanks.
Upvotes: 2
Views: 947
Reputation: 251
Use @selector(caseInsensitiveCompare:) with your fetchRequest like:
NSSortDescriptor *sortDescr = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Car"];
[fetchRequest setSortDescriptors:@[sortDescr]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name matches[c] %@", @"gmc"]];
Then perform your fetch as usual.
Upvotes: 0
Reputation: 535
The keywords "like" and "contains" seem to work just fine.
fetch.predicate = [NSPredicate predicateWithFormat:@"name like[c] %@", @"gmc"];
or
fetch.predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", @"gmc"];
More keyword options and details can be found here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-CJBDBHCB
and here http://nshipster.com/nspredicate/
Upvotes: 1
Reputation: 491
Try below code:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UPC ==[c] %@ OR ItemID ==[c] %@", aUPCCode,aUPCCode];
Upvotes: 1