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

后端 未结 2 561
余生分开走
余生分开走 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:06

    Well, the enumerateObjectsUsingBlock: method of NSArray will let you enumerate the objects in the array using a block (per your request).

    To test for strings, you could simply do this:

    if ([itemToTest isKindOfClass:[NSString class]]) ...
    

    And you could add each of those to a Dictionary with Object keys and Int values (or vice-versa).

    0 讨论(0)
  • 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];
    }
    
    0 讨论(0)
提交回复
热议问题