Vah.Sah
Vah.Sah

Reputation: 532

Core Data and NSPredicate

I'm looking for a way to use NSPredicate to set a "beginswith [cp]" condition to fetch objects. In the data model there is an one entity which contains 4 basic attributes. Name of first attribute is cityName. The goal is to find records for which cityName begins with given character, but I'm not sure how to format the predicate. This is part of my code for this

NSString * lastCharacter = [userCity substringFromIndex:[userCity length] -1];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];

NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:@"Cities"
            inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(cityName = beginswith [cp] %@ )", lastCharacter];
[request setPredicate:pred];

but for this code I get following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(cityName = beginswith [cp] %@ )"'

Upvotes: 0

Views: 90

Answers (2)

Mundi
Mundi

Reputation: 80265

The problem is that the beginswith is an operator, so = beginswith is one too much. The brackets in your predicate are also not necessary. Thus:

[NSPredicate predicateWithFormat:@"cityName beginswith[cd] %@", lastCharacter];

Upvotes: 1

Hussain Shabbir
Hussain Shabbir

Reputation: 14995

Just change your predicate like this :-

   NSPredicate *pred = [NSPredicate predicateWithFormat:@"cityName contains[cd] %@",lastCharacter];

Upvotes: 0

Related Questions