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

标签 ios objective-c nsarray

我有以下两个数组。

 NSArray *array1=[[NSArray alloc]initWithObjects:@"ABC",@"DEF", nil];
 NSArray *array2=[[NSArray alloc]initWithObjects:@"ABC",@"123",@"DEF",@"DEF", nil];

现在我必须搜索 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
    //
    //
    //

}

最佳答案

根据 NSSet 文档,集合 的成员资格测试比数组 更快。 因此,首先将 array1 转换为集合是有意义的:

NSSet *set1 = [NSSet setWithArray:array1];

然后测试 array2 的每个对象是否属于该集合。这个可以方便 完成

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

显示所有匹配的索引:

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

更新:(问题编辑后)不,没有用匹配对象的索引填充 NSArray 的方法。但是有一种方法可以填充 NSIndexSetNSIndexSet 是一个专门存放索引的集合 到一些其他数据结构,例如数组。然后你的代码看起来像

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

但我不知道它是否对性能有很大影响。

关于ios - 在 iOS 的 NSArray 中获取匹配对象索引的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19836047/

相关文章:

ios - 获取动态表格 View 单元格高度和自动释放

ios - 如何通过 NSUserDefault 字典的键使用 For 循环

iOS 12 DatePicker 值更改问题

iphone - 自定义分组表单元格

objective-c - 如何将上下文相关菜单添加到 NSOutlineView(即右键单击菜单)

objective-c - 多个 valueForKey : calls give different results than valueForKeyPath: using same keys

objective-c - NSRangeException 困惑

iphone - Objective-C - 从今天(明天)开始的第二天

ios - 使用 UIImagePickerController 捕获图像而不保存在设备上

objective-c - ShareKit - 如何访问 Twitter 用户名