使用NSPredicate搜索模型

时间:2017-06-12 10:44:27

标签: ios objective-c nspredicate

以下是我的模型类

{"ID":1,"Name":"Area 1","Code":"xyz","StartTime":"09:30","EndTime":"13:40"},
{"ID":2,"Name":"Area 2","Code":"xyz","StartTime":"09:00","EndTime":"13:40"},
{"ID":3,"Name":"Area 3","Code":"xyz","StartTime":"10:30","EndTime":"14:40"},
{"ID":4,"Name":"Area 4","Code":null,"StartTime":"09:30","EndTime":"13:30"}]

我已经在NSMutableArray中检索了模型类值并在TableView上显示,现在我需要从模型类中搜索名称,下面是我的代码,但它没有工作。

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    NSString *searchString = searchController.searchBar.text;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS [cd] %@", searchString];
    for (NSString *key in _arrAlreaList) {

        NSArray *array = [_arrAlreaList valueForKey:key];
        NSArray *tempArray = [array filteredArrayUsingPredicate:predicate];

        if (tempArray.count > 0) {
            [filteredArray addObjectsFromArray:tempArray];
            [self.tblArea reloadData];
        }
    }
  }

1 个答案:

答案 0 :(得分:1)

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {

   NSString *searchString = searchController.searchBar.text;
   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.Name contains [c] %@", searchString];
   NSArray *resultArray = [_arrAlreaList filteredArrayUsingPredicate:predicate];
   NSLog(@"Result Array %@",resultArray);

} 

试试这个!!