0

我只是在寻找一种更好、更有效的方法来遍历给定的对象数组,并将NSString每个对象的属性与另一个仅包含 NSStrings 的数组进行比较。

我当前的代码使用两个 for-each 循环,但它认为这不是最有效的方法。

for (MYClass *foo in arrayOfMyClass) {
    for (NSString *ID in arrayOfStringIDs) {
        if ([foo.Id isEqualToString:ID]) {
            //Do something
            break;
        }
    }
}

我认为应该有可能通过一些很酷的技巧来放弃至少一个循环。

4

3 回答 3

4

如果您只想知道是否foo.Id存在于 中arrayOfStringIDs,请改用 NSSet 字符串。然后你可以这样做:

NSSet * mySetOfStringIDs = [NSSet setWithArray:arrayOfStringIDs];
for(MyClass * foo in arrayOfMyClass) {
    if([mySetOfStringIDs containsObject:foo.Id]) {
        // Do something
        break;
    }
}

这避免了第二个循环,因为containsObject:对于一个集合来说通常比​​ O(n) 快得多。当然,您应该根据需要进行自己的分析。

于 2012-07-18T21:54:51.820 回答
1

检查 Nsarray 的 indexofobject 方法。可能它可以帮助您直接获取索引而不是 nsarray 中字符串的循环。

于 2012-07-18T21:50:33.460 回答
0

If you want to get an array of strings that exist in both arrayOfMyClass and arrayOfStringIDs then you could use key-value coding to pull the set of strings out of arrayOfMyClass and intersect the resulting set with arrayOfStringIDs. If your class is KVC compliant then you can get all the Id strings out of it as a set:

NSMutableSet *idSet=[NSMutableSet setWithArray:[arrayOfMyClass 
   valueForKeyPath:@"@distinctUnionOfObjects.Id"]];
[idSet intersectSet:[NSSet setWithArray:arrayOfStringIDs]];
NSArray *idArray=[idSet allObjects];

Unfortunately there is not a method to intersect two NSArrays which is why they have to be turned into a set first.

于 2012-07-19T05:07:07.320 回答