对于这种 2 倍快速枚举,有更好的解决方案吗?
我正在循环访问一个数组,并将该数组中的对象标记属性与另一个数组中的对象进行比较。
这是我的代码:
NSArray *objectsArray = ...;
NSArray *anotherObjectArray = ...;
NSMutableArray *mutableArray = ...;
for (ObjectA *objectA in objectsArray) {
for (ObjectZ *objectZ in anotherObjectArray) {
if ([objectA.tag isEqualToString:objectZ.tag]) {
[mutableArray addObject:objectA];
}
}
}
有更好的方法吗?
请注意 tag
属性不是整数,因此必须比较字符串。
I'm looping through an array and comparing the objects tag property in this array with the objects in another array.
Here's my code:
NSArray *objectsArray = ...;
NSArray *anotherObjectArray = ...;
NSMutableArray *mutableArray = ...;
for (ObjectA *objectA in objectsArray) {
for (ObjectZ *objectZ in anotherObjectArray) {
if ([objectA.tag isEqualToString:objectZ.tag]) {
[mutableArray addObject:objectA];
}
}
}
Is there a better way to do this?
Please note the tag
property is not an integer, so have to compare strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过迭代每个数组一次而不是嵌套来完成此操作:
You can do this by iterating over each array once, rather than nesting:
也许你可以使用 [NSArray FilteredArrayUsingPredicate:]; - http://developer.apple .com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html
但是您可能需要自己调整属性标签。
希望这有帮助
May be you can use [NSArray filteredArrayUsingPredicate:]; - http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html
But you may have to tweak for property tag yourself.
Hope this helps
好吧,最简单的更改(因为每个 objectA 只能有一个匹配项),那么您可以在 [mutableArray addObject:objectA] 之后进行中断。当匹配发生时,内部循环会减少 50%。
更戏剧性的是,如果您经常这样做并且 anotherObjectArray 的顺序并不重要,则可以反转 anotherObjectArray 数据结构并使用字典,按标签存储对象。然后,您只需迭代 objectA 询问其标签是否在 ObjectZ 的字典中。
Well, the simplest change (as there can only be one match per objectA) then you could do a break after your [mutableArray addObject:objectA]. When a match occurs, that would reduce the inner loop by 50%.
More dramatically, if you're doing this a lot and the order of anotherObjectArray doesn't matter, would be to invert your anotherObjectArray data structure and use a dictionary, storing the objects by tag. Then you just iterate over objectA asking if its tag is in the dictionary of ObjectZs.
感谢所有的答案。虽然我已经接受了 NSMutableSet 解决方案,但实际上我最终选择了以下解决方案,因为事实证明它更快一点:
Thanks for all the answers. While I have accepted the NSMutableSet solution, I actually ended up going with the following, as it turned out it was a tiny bit faster: