3

你如何创建一个 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”等)..

4

3 回答 3

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

于 2013-01-15T14:46:10.877 回答
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];
于 2013-01-15T15:32:54.637 回答
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];
于 2013-01-15T14:49:05.773 回答