2

NSArray只有我可以找到值:

NSArray *arr = [NSArray arrayWithObjects:@"299-1-1", @"299-2-1", @"299-3-1", @"399-1-1", @"399-2-1", @"399-3-1", @"499-1-1", @"499-2-1", @"499-3-1", nil];
NSString *search = @"299";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",[NSString stringWithFormat:@"%@", search]];
NSArray *array = [arr filteredArrayUsingPredicate: predicate];
NSLog(@"result: %@", array);

Found Result正如预期的那样:

 result: (
 "299-1-1",
 "299-2-1",
 "299-3-1"
 )

但是为了NSArray拥有NSArrayNSString

NSArray *arr = [NSArray arrayWithObjects:[NSArray arrayWithObjects:@"299-1-1", nil],[NSArray arrayWithObjects:@"399-1-1", nil],[NSArray arrayWithObjects:@"499-1-1", nil], nil];

这里会有什么predicate syntax????

4

3 回答 3

14

要在嵌套数组中搜索,您可以在谓词中使用“ANY”运算符:

NSArray *arr = [NSArray arrayWithObjects:[NSArray arrayWithObjects:@"299-1-1", nil],[NSArray arrayWithObjects:@"399-1-1", nil],[NSArray arrayWithObjects:@"499-1-1", nil], nil];
NSString *search = @"299";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF CONTAINS %@", search];
NSArray *array = [arr filteredArrayUsingPredicate: predicate];
NSLog(@"result: %@", array);

输出:

(
    (
        “299-1-1”
    )
)
于 2013-04-17T13:14:22.997 回答
4

如果您想提供一组 searchTerms,那么您需要更改您的谓词。

像这样的事情会做到这一点

NSArray *arr         = @[ @"299-1-1", @"299-2-1", @"299-3-1", @"399-1-1", @"399-2-1", @"399-3-1", @"499-1-1", @"499-2-1", @"499-3-1" ];
NSArray *searchTerms = @[ @"299", @"399" ];

NSPredicate *predicate = [NSPredicate predicateWithBlock:^ (id evaluatedObject, NSDictionary *bindings) {   
  for (NSString *searchTerm in searchTerms) {
    if (NSNotFound != [evaluatedObject rangeOfString:searchTerm].location) {
      return YES;
    }   
  }
  return NO;
}];

NSArray *array = [arr filteredArrayUsingPredicate:predicate];
NSLog(@"result: %@", array);
//#=> result: (
  "299-1-1",
  "299-2-1",
  "299-3-1",
  "399-1-1",
  "399-2-1",
  "399-3-1"
)
于 2013-04-17T12:48:07.133 回答
-1
NSArray *arr = [NSArray arrayWithObjects:[NSArray arrayWithObjects:@"299-1-1", nil],[NSArray arrayWithObjects:@"399-1-1", nil],[NSArray arrayWithObjects:@"499-1-1", nil], nil];
NSString *search = @"299";
NSMutableArray *filteredArray = [[NSMutableArray alloc] init];
for (NSArray *array in arr) {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self CONTAINS %@",search];
    if([array filteredArrayUsingPredicate:predicate].count)
    {
        [filteredArray addObject:[array filteredArrayUsingPredicate:predicate]];
    }
}
NSLog(@"%@", filteredArray);
于 2013-04-17T12:31:02.747 回答