yinkou
yinkou

Reputation: 5766

More efficient way to iterate through an array of NSStrings and compare them

I'm just looking for a nicer and more efficient way to iterate through a given array of objects and compare a NSString property of each to another array just containing NSStrings.

My current code uses two for-each loops but it don't think that it is the most efficient way.

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

I think that it should be somehow possible to drop at least one loop with some cool tricks.

Upvotes: 0

Views: 609

Answers (3)

David G
David G

Reputation: 5784

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.

Upvotes: 0

Tim
Tim

Reputation: 60110

If all you want to know is if foo.Id exists in arrayOfStringIDs, use an NSSet of strings instead. Then you can do:

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

This avoids the second loop, since containsObject: is generally much faster than O(n) for a set. You should, of course, do your own profiling as needed.

Upvotes: 4

iCreative
iCreative

Reputation: 1506

Check for indexofobject method of Nsarray. May be it can help you to get the index directly instead of a loop for the string in nsarray.

Upvotes: 1

Related Questions