Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate compare with Integer

How can I compare two NSNumbers or a NSNumber and an Integer in an NSPredicate?

I tried:

NSNumber *stdUserNumber = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:@"standardUser"]];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"userID == %@", stdUserNumber];

Well, this doesn't work ... anyone has an idea how to do it? I'm sure it's pretty easy but I wasn't able to find anything ...

like image 651
wolfrevo Avatar asked Sep 24 '11 16:09

wolfrevo


2 Answers

NSNumber is an object type. Unlike NSString, the actual value of NSNumber is not substitued when used with %@ format. You have to get the actual value using the predefined methods, like intValue which returns the integer value. And use the format substituer as %d as we are going to substitute an integer value.

The predicate should be,

predicateWithFormat:@"userID == %d", [stdUserNumber intValue]];
like image 170
EmptyStack Avatar answered Nov 12 '22 08:11

EmptyStack


If you are using predicateWithSubstitutionVariables: and value you want to predicate is NSNumber with integer value then you need to use NSNumber in predicate instead of NSString as substitution value. Take a look at example:

NSPredicate *genrePredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"genreID == $GENRE_ID"]]; //if we make only one NSPredicate if would look something like this: [NSPredicate predicateWithFormat:@"genreID == %d", [someString integerValue]];

NSPredicate *localPredicate = nil;
for(NSDictionary *genre in genresArray){
    localPredicate = [genrePredicate predicateWithSubstitutionVariables:@{@"GENRE_ID" : [NSNumber numberWithInteger:[genre[@"genre_id"] integerValue]]}];
}
like image 3
Josip B. Avatar answered Nov 12 '22 07:11

Josip B.