obj c -get list of indexes in NSArray from NSPredicate

自作多情 提交于 2019-12-14 04:26:02

问题


I have an array of car and I am filtering it based on objects containing the letter i.

NSMutableArray *cars = [NSMutableArray arrayWithObjects:@"Maruthi",@"Hyundai", @"Ford", @"Benz", @"BMW",@"Toyota",nil];
NSString *stringToSearch = @"i";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",stringToSearch]; // if you need case sensitive search avoid '[c]' in the predicate
NSArray *results = [cars filteredArrayUsingPredicate:predicate];

results contains Maruthi,Hyundai. Instead of the elements, I want results to contain the indexes of the elements i.e 0,1.


回答1:


NSMutableArray *cars = [NSMutableArray arrayWithObjects:@"Maruthi",@"BMW", @"Ford", @"Benz", @"Hyundai",@"Toyota",nil]; NSMutableArray * results = [[NSMutableArray alloc]init];

for(int i = 0;i<cars.count;i++)
{
    NSString * obj = [cars objectAtIndex:i];
    if([obj rangeOfString:@"i"].location == NSNotFound)
    {
        NSLog(@"Not Found");
    }
    else
    {
        int index = [cars indexOfObject:obj];
        [results addObject:[NSNumber numberWithInt:index]];
    }
}



回答2:


Why not use

- (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate

Or similar?

Depending on your search criteria, something like this perhaps?

    NSArray *array = @[@"Maruthi",@"Hyundai", @"Ford", @"Benz", @"BMW", @"Toyota"];
    NSString *stringToSearch = @"i";
    NSIndexSet *set = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
       NSString *string = obj;
       if (([string rangeOfString:stringToSearch].location == NSNotFound))
       {
           return NO;
       }
       return YES;
    }];


来源:https://stackoverflow.com/questions/20344435/obj-c-get-list-of-indexes-in-nsarray-from-nspredicate

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