2014-03-28 46 views
1

我是NSPredicates的新手,但我知道基礎知識。NSPredicate - 帶參數的動態謂詞

這是我的謂語現在的樣子:

[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 
} 

我想這樣做,以便我可以有幾個基謂語然後將參數放在它們上進行搜索。我不想再次創建我的謂詞。

希望你能理解。

謝謝!

回答

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/

0

看起來好像我剛剛找到答案。我可以用predicateWithSubstitutionVariables這樣的:

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

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

NSPredicate *filter = [resultPredicate predicateWithSubstitutionVariables:sub];