NSPredicate - Dynamic predicate with arguments

删除回忆录丶 提交于 2019-12-24 00:39:42

问题


I am new to NSPredicates, but I know the basics.

This is how my predicate looks now:

[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];

What I want to do, is to be able to create a predicate like this (Pseudo code):

NSPredicate *myPredicate = [NSPredicate predicateWithBaseString:@"name contains[c] _ARGUMENT_"];

And then use it in, for example a loop (pseudo code):

for(NSString *searchString in self.allStrings)
{
    NSPredicate *myNewPredicate = [myPredicate predicateWithArgument:searchString];
    //Here I do the searchOperations with my new predicate
}

I want to do this so that I can have a few base predicates and then put parameters on them for searching. I do not want to create my predicate again.

Hopefully you understand.

Thank you!


回答1:


Use following

NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"name contains[c] $ARGUMENT"];

for(NSString *searchString in self.allStrings)
{
    NSPredicate *myNewPredicate = [myPredicate predicateWithSubstitutionVariables:@{@"ARGUMENT" :searchString}];
    //Here I do the searchOperations with my new predicate
}

also I suggest to read this article http://nshipster.com/nspredicate/




回答2:


It seems as if i just found the answer. I can use predicateWithSubstitutionVariables like this:

NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] $searchText"];

NSDictionary *sub = [NSDictionary dictionaryWithObject:searchText forKey:@"searchText"];

NSPredicate *filter = [resultPredicate predicateWithSubstitutionVariables:sub];


来源:https://stackoverflow.com/questions/22710225/nspredicate-dynamic-predicate-with-arguments

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