问题
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