使用块枚举 NSArray 以查找和存储数组中所有 NSString 的所有索引



我如何枚举一个包含多种类型对象的NSArray,以获得找到NSString的所有索引,然后能够通过说这样的话来按顺序引用每个索引。。。

NSString *firstOccurrence = [myArray objectAtIndex:firstOccurrence];
NSString *secondOccurrence = [myArray objectAtIndex:secondOccurrence];
NSString *thirdOccurrence = [myArray objectAtIndex:thirdOccurrence];

谢谢!

编辑:我是如何使用代码的(用@NJones示例更新。)

我需要字符串存储在数组中的索引的整数值,以使用该值更新NSUInteger属性"wordDisplayed"。

在我的代码中,我使用UIActionSheet的修改版本来接受块:https://github.com/zoul/Lambda-Alert

NSIndexSet *stringLocations = [arrayInLesson indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
    return [(NSObject *)obj isKindOfClass:[NSString class]];
}];
NSArray *passingObjects = [arrayInLesson objectsAtIndexes:stringLocations];
sectionHeadersAct = [[LambdaSheet alloc] initWithTitle:@"Book 2 Lesson 1"];
[sectionHeadersAct addButtonWithTitle:@"D. E. F. & G. Teach New Letters" block:^{ 
    //Do nothing yet
}];
[sectionHeadersAct addButtonWithTitle:[passingObjects objectAtIndex:0] block:^{
    NSLog(@"First");
    wordDisplayed = theIndexOfThisStringIn_arrayInLesson;
}];
[sectionHeadersAct addButtonWithTitle:[passingObjects objectAtIndex:1] block:^{ 
    NSLog(@"Second"); 
    wordDisplayed = theIndexOfThisStringIn_arrayInLesson;
}];
[sectionHeadersAct addButtonWithTitle:[passingObjects objectAtIndex:2] block:^{ 
    NSLog(@"Third"); 
    wordDisplayed = theIndexOfThisStringIn_arrayInLesson;
}];
[sectionHeadersAct addButtonWithTitle:[passingObjects objectAtIndex:3] block:^{ 
    NSLog(@"Fourth"); 
    wordDisplayed = theIndexOfThisStringIn_arrayInLesson;
}];
[sectionHeadersAct setDismissAction:^{
    //Do nothing yet
}];
[sectionHeadersAct showInView:self.view];

您可以获得使用indexesOfObjectsPassingTest:定义的对象位置的NSIndexSet。像这样:

-(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];
}

好吧,NSArrayenumerateObjectsUsingBlock:方法将允许您使用块(根据您的请求)枚举数组中的对象。

要测试字符串,您可以简单地执行以下操作:

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

您可以将其中的每一个添加到具有Object键和Int值的Dictionary中(反之亦然)。

最新更新