Reuse NSPredicate for new variable substitute

不打扰是莪最后的温柔 提交于 2019-11-29 03:33:50

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/7708541/reuse-nspredicate-for-new-variable-substitute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!