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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With