NSPredicate按字母过滤

时间:2013-01-15 14:30:29

标签: ios objective-c

如何制作NSPredicate,查找包含特定字母的数组中的所有对象?

NSMutableArray *testArray = [[NSMutableArray alloc] initWithObjects:@"abc",@"cba", @"bca", nil];

NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",@"abc"];

NSMutableArray *result = (NSMutableArray *)[testArray filteredArrayUsingPredicate: p];

结果只包含一个对象,@“abc”...我希望它能捕获所有包含“abc”的单词。 (例如“cba”,“cba”,“lllllllllbbacllllll”等)..

3 个答案:

答案 0 :(得分:2)

我不知道是否可以使用单个谓词,但您可以使用NSCompoundPredicate构建复合谓词:

NSMutableArray *testArray = [[NSMutableArray alloc] initWithObjects:@"abc",@"cba", @"bca", nil];

NSMutableArray *predicates = [NSMutableArray array];
for (NSString *substring in @[@"a", @"b", @"c"]) {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", substring];
    [predicates addObject:predicate];
}
NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];

NSArray *result = [testArray filteredArrayUsingPredicate:compoundPredicate];

另请参阅Nicolas对filteredArrayUsingPredicate的评论。

答案 1 :(得分:2)

其他答案没有错。但是,我想建议一种不同的方法来创建谓词:使用块。

NSArray *testArray = @[@"abc", @"cba", @"cda"];
NSArray *letters = @[@"a", @"b", @"c"];

NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id string, NSDictionary *bindings) {
    for ( NSString *letter in letters ) {
        NSStringCompareOptions options = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
        if ( ! [string rangeOfString:letter options:options].length ) {
            return NO;
        }
    }
    return YES;
}];
NSArray *result = [testArray filteredArrayUsingPredicate:p];

只是为了好玩,你也可以用子查询编写谓词。效率较低,但这是较短的解决方案。

NSArray *testArray = @[@"abc", @"cba", @"bcda"];
NSArray *letters = @[@"a", @"b", @"c"];

NSPredicate *p = [NSPredicate predicateWithFormat:@"SUBQUERY(%@, $a, self CONTAINS[cd] $a)[SIZE] == %d", letters, letters.count];
NSArray *result = [testArray filteredArrayUsingPredicate:p];

答案 2 :(得分:1)

单独测试角色,试一试:

NSMutableArray *testArray = [[NSMutableArray alloc] initWithObjects:@"abc",@"cba", @"bca", nil];
NSPredicate *p = [NSPredicate predicateWithFormat:@"self contains 'a' && self contains 'b' && self contains 'c'"];
NSMutableArray *result = [[testArray filteredArrayUsingPredicate: p] mutableCopy];