Find values in NSArray having NSArray with NSString using NSPredicate iOS

感情迁移 提交于 2019-12-19 04:14:50

问题


With NSArray only i can find values as:

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 as expected :

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

But for NSArray having NSArray with NSString

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

What will be predicate syntax here?????


回答1:


To search in a nested array, you can use the "ANY" operator in the predicate:

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);

Output:

(
    (
        "299-1-1"
    )
)



回答2:


If you want to provide an array of searchTerms then you'll need to change your predicate.

Something like this would do it

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"
)



回答3:


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);


来源:https://stackoverflow.com/questions/16060026/find-values-in-nsarray-having-nsarray-with-nsstring-using-nspredicate-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!