NSPredicate - 带参数的动态谓词

时间:2014-03-28 10:29:39

标签: ios core-data nspredicate

我是NSPredicates的新手,但我知道基础知识。

这就是我的谓词现在的样子:

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

我想做的是能够创建这样的谓词(伪代码):

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

然后使用它,例如循环(伪代码):

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

我想这样做,以便我可以有一些基本谓词,然后在其上放置参数进行搜索。我不想再次创建我的谓词了。

希望你明白。

谢谢!

2 个答案:

答案 0 :(得分:1)

使用以下

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
}

我还建议你阅读这篇文章http://nshipster.com/nspredicate/

答案 1 :(得分:0)

好像我刚刚找到了答案。我可以像这样使用predicateWithSubstitutionVariables:

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

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

NSPredicate *filter = [resultPredicate predicateWithSubstitutionVariables:sub];
相关问题