Enumerate NSArray using blocks to find and store all indexe's of all NSStrings in array

后端 未结 2 562
余生分开走
余生分开走 2021-01-28 00:43

How could I enumerate an NSArray containing objects of multiple types, to get all the indexes where an NSString is found, then be able to refer to each index in order by saying

2条回答
  •  一整个雨季
    2021-01-28 01:20

    You can get an NSIndexSet of the location of objects that you define with indexesOfObjectsPassingTest:. Like so:

    -(void)findStrings{
        NSArray *randomObjects = [NSArray arrayWithObjects:[NSNull null], @"String", [NSNull null], @"String", [NSNull null], nil];
        NSIndexSet *stringLocations = [randomObjects indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
            return [(NSObject *)obj isKindOfClass:[NSString class]];
        }];
        NSLog(@"strings %@",stringLocations);
    
            // You can get an array of just the passing objects like so:
        NSArray *passingObjects = [randomObjects objectsAtIndexes:stringLocations];
    }
    

提交回复
热议问题