Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse NSPredicate for new variable substitute

Can I reuse NSPredicate for new variable substitute? My NSPredicate is rather simple:

NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"id == %@",userID];

The userID is generated at run-time with different value, right now for each userID I need to create a NSPredicate. So is it possible I can reuse my NSPredicate ?

like image 680
Qiulang 邱朗 Avatar asked Oct 10 '11 04:10

Qiulang 邱朗


1 Answers

Yep, you can do this with a variable:

NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"id == $user"];

Save that predicate somewhere, then do this when you need to actually start filtering stuff:

NSDictionary *sub = [NSDictionary dictionaryWithObject:user forKey:@"user"];
NSPredicate *filter = [userPredicate predicateWithSubstitutionVariables:sub];

This is a much more efficient way to reuse a predicate, because parsing the format string (which can be pretty expensive) only happens once.

like image 117
Dave DeLong Avatar answered Nov 04 '22 11:11

Dave DeLong