【问题标题】:Fastest way to iterate through an NSArray with objects and keys使用对象和键迭代 NSArray 的最快方法
【发布时间】:2010-03-31 01:50:03
【问题描述】:
我在下面有一个名为“objects”的 NSArray,arrayCount = 1000。遍历这个数组大约需要 10 秒。有没有人有更快的方法来遍历这个数组?
for (int i = 0; i <= arrayCount; i++) {
event.latitude = [[[objects valueForKey:@"CLatitude"] objectAtIndex:i] floatValue];
event.longitude = [[[objects valueForKey:@"CLongitude"] objectAtIndex:i] floatValue];
}
【问题讨论】:
标签:
objective-c
ios
performance
nsarray
iteration
【解决方案1】:
迭代 NSArray 的最快方法是使用 fast enumeration。我的情况是:
for (id object in objects) {
event.latitude = [[object valueForKey:@"CLatitude"] floatValue];
event.longitude = [[object valueForKey:@"CLongitude"] floatValue]
}
【解决方案2】:
看起来 valueForKey 返回的数组在每次迭代时都是相同的,因此请尝试在循环外获取对它们的引用:
NSArray *latitudes = [objects valueForKey:@"CLatitude"];
NSArray *longitudes = [objects valueForKey:@"CLongitude"];
for (int i = 0; i <= arrayCount; i++) {
event.latitude = [[latitudes objectAtIndex:i] floatValue];
event.longitude = [[longitudes objectAtIndex:i] floatValue];
}
但是循环的意义何在?最后,不就是将事件属性设置为两个数组中的最后一个值吗?另外,如果 arrayCount 是元素的数量,那么循环应该是 i < arrayCount 而不是 i <= arrayCount。