如何基于nsarray过滤谓词

如何基于nsarray过滤谓词

我有以下uisearchbar委托方法。我希望此方法搜索我的对象的arrayofterms属性,以查看是否有任何元素与searchText参数匹配。

这样行吗? :

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {


    [self.filteredArray removeAllObjects];
    // something like this is what the objects array attribute will look like: NSArray *arrayofterms = [NSArray arrayWithObjects:@"Miguel", @"Ben", @"Adam", @"Melissa", nil];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.arrayofterms contains[c] %@",searchText];
    self.filteredArray = [NSMutableArray arrayWithArray:[self.planDataArray filteredArrayUsingPredicate:predicate]];

    }

最佳答案

数组是否包含字符串?然后 ...

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSString *string, NSDictionary *bind) {
    return [string isEqualToString:searchText];
}];

self.filteredArray = [[self.planDataArray filteredArrayUsingPredicate:predicate] mutableCopy];


如果planDataArray包含其他种类的对象,可能是自定义对象,则...

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(MyCustomObject *object, NSDictionary *bind) {
    NSString *string = object.someStringProperty;
    return [string isEqualToString:searchText];
}];

关于ios - 如何基于nsarray过滤谓词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24816571/

10-12 03:19