NSPredicate compare with Integer

wolfrevo picture wolfrevo · Sep 24, 2011 · Viewed 37.4k times · Source

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 ...

Answer

EmptyStack picture EmptyStack · Sep 24, 2011

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]];