我有一个包含字典对象的NSArray。数组的结构如下所示:
Data = (
{
Date = "07/11/2013";
LotNumber = 1;
PartyName = "Gaurav Wadhwani";
Quantity = 500;
},
{
Date = "07/11/2013";
LotNumber = 2;
PartyName = "Gaurav Wadhwani";
Quantity = 600;
}
)
我正在使用搜索和显示控制器,该控制器允许用户搜索LotNumber
,PartyName
或Date
。我知道如何使用Scope标题和搜索栏。但是,我无法使用NSPredicate来获得正确的结果。这是我的代码:
NSString *searchParameter = @"LotNumber";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", searchParameter, searchText];
filteredGoodsArray = [NSMutableArray arrayWithArray:[data filteredArrayUsingPredicate:predicate]];
NSLog(@"Filtered Array = %@", filteredGoodsArray);
我总是在过滤后的数组中得到空白结果。你能告诉我这里有什么问题吗?
谢谢。
答案 0 :(得分:2)
您可以使用 -predicateWithBlock:来过滤dataArray
- (NSArray *)filterArray:(NSArray *)dataArray WithSearchText:(NSString *)searchText ScopeTitle:(NSString *)scopeTitle {
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
//this is the dictionary in your dataArray
NSDictionary *dictionary = (NSDictionary *)evaluatedObject;
NSString *key = @"";
//get key based on your selected scope
if ([scopeTitle isEqualToString:@"Lot"])
key = @"LotNumber";
else if ([scopeTitle isEqualToString:@"Party"])
key = @"PartyName";
//grab the value from the dictionary with the corresponding key
NSString *value = [dictionary objectForKey:key];
//if the value contains your searchText return YES to add the object to the filtered array
//if not it returns NO to filter it out of the array
return [value rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound;
}];
//filter your dataArray using the predicate
return [dataArray filteredArrayUsingPredicate:predicate];
}