gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:18:57 26 4
gpt4 key购买 nike

我有以下两个数组。

 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com