在iOS中获取NSArray中匹配对象索引的最佳方法?

Ash*_*hok 3 objective-c nsarray ios

我有以下两个数组.

 NSArray *array1=[[NSArray alloc]initWithObjects:@"ABC",@"DEF", nil];
 NSArray *array2=[[NSArray alloc]initWithObjects:@"ABC",@"123",@"DEF",@"DEF", nil];
Run Code Online (Sandbox Code Playgroud)

现在我必须搜索每个array1的对象和array2,并需要获取匹配的索引.我的应用程序在array2中包含超过一千个对象.

请建议除了将第二个for循环放在第一个for循环之外的最佳方法

for (int i=0; i<array1.count; i++)
{
//Need to search the [array1 objectAtIndex:i] string in array2 and need to get the matched indexes into an array in best optimised way here.

    NSMutableArray *matchedIndexesArray=[[NSMutableArray alloc]init];
    NSString *stringToSearch=[array1 objectAtIndex:i];

    //here i can put another array like below to get the matched indexes..but is there any optimized way other than this for loop here? or is there any simple inbuilt method to get the matched objects into an array here.
    for (int j=0; j<array2.count; j++)
    {
        if ([stringToSearch isEqualToString:[array2 objectAtIndex:j]])
        {
            [matchedIndexesArray addObject:[NSString stringWithFormat:@"%d",j]];
        }
    }

    NSLog(@"matchedIndexesArray-->%@<--",matchedIndexesArray);
    //I will use this matchedIndexesArray here further processing...
    //
    //
    //
    //Large Code Here
    //
    //
    //

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 11

根据NSSet文档,成员测试对于集合而言比对阵列更快.因此,array1首先转换为集合是有意义的:

NSSet *set1 = [NSSet setWithArray:array1];
Run Code Online (Sandbox Code Playgroud)

然后测试array2集合中成员资格的每个对象.这可以方便地完成

NSIndexSet *matchingIndexes = [array2 indexesOfObjectsPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
    return [set1 containsObject:obj];
}];
Run Code Online (Sandbox Code Playgroud)

显示所有匹配的索引:

[matchingIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
    NSLog(@"%ld", (long)idx);
}];
// Output: 0, 2, 3
Run Code Online (Sandbox Code Playgroud)

更新:(问题编辑后)否,没有方法来填充NSArray匹配对象的索引.但是有一种方法可以填补NSIndexSet.NSIndexSet是一个特殊的集合,用于将索引存储到其他一些数据结构中,例如数组.然后你的代码看起来像

for (NSString *stringToSearch in array1) {
    NSIndexSet *matchingIndexes = [array2 indexesOfObjectsPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
        return [stringToSearch isEqualToString:obj];
    }];

    NSLog(@"matchingIndexes: %@", matchingIndexes);

    // Work with matchingIndex, for example enumerate all indices:
    [matchingIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        NSLog(@"%ld", (long)idx);
    }];
}
Run Code Online (Sandbox Code Playgroud)

但我不知道它在性能方面是否有很大差异.