2011-12-19 62 views
1

是否可以將保留字,特別是ORAND替換爲predicateFormat+ [NSPredicate predicateWithFormat]替代保留字

我想:

NSString *andOr = (isAnd ? @"AND" : @"OR"); // isAnd is a BOOL variable 
NSPredicate *predicate = [NSPredicate predicateWithFormat: 
          @"firstName == %@ %K lastName == %@", 
          user.firstName, andOr, user.lastName]; 

但我得到:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: 'Unable to parse the format string "firstName == %@ %K lastName == %@" 

我試圖%s(也%S),而不是%K,但得到了同樣的異常。

我現在的工作解決方案是單獨創建predicateFormat

NSString *predicateFormat = [NSString stringWithFormat: 
          @"firstName == %%@ %@ lastName == %%@", andOr]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat, 
          user.firstName, user.lastName]; 

但是,我想知道,這可以在不另行創建predicateFormat來完成。

回答

1

是的,它可以:

NSPredicate *firstName = [NSPredicate predicateWithFormat:@"firstName == %@", [user firstName]]; 
NSPredicate *lastName = [NSPredicate predicateWithFormat:@"lastName == %@", [user lastName]]; 
NSArray *subpredicates = [NSArray arrayWithObjects:firstName, lastName, nil]; 

NSPredicate *predicate = nil; 
if (isAnd) { 
    predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates]; 
} else { 
    predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates]; 
} 
0

使用搜索欄文本我正在篩選數據。

下面代碼是簡單,無需任何解釋

的NSString * predFormat = [NSString的stringWithFormat:@「姓CONTAINS並[c] '%@' OR名字CONTAINS並[c] '%@' 或電話CONTAINS [c]'%@'「,searchValue,searchValue,searchValue]; // Like

NSPredicate * predicate = [NSPredicate predicateWithFormat:predFormat];

NSArray * tempData = [array filteredArrayUsingPredicate:predicate];

希望這會對你有用.. 快樂編碼....