syedfa
syedfa

Reputation: 2809

How to do fast enumeration to populate an NSDictionary using two NSArray's in Objective-C?

I have two arrays, one that holds key values (myKeys), and the other holds NSString objects(myStrings). I would like to use both arrays to populate a single NSDictionary (myDictionary)using fast enumeration but am not sure how?

for (NSNumber *key in myKeys) {

   [self.myDictionary setObject @"here is where the value should go from the 'other' array forKey: key];

}

How would I factor in the NSArray object here?

Upvotes: 0

Views: 387

Answers (3)

Thomas Keuleers
Thomas Keuleers

Reputation: 6115

If you really want to speed up your for-loop, you could your the NSEnumerationConcurrent option. This enumeration option makes sure you're using all the resources available on your iDevice.

[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *key, NSUInteger idx, BOOL *stop) {
    [self.myDictionary setObject @"here is where the value should go from the 'other' array" forKey: key];
}];

For more information on concurrent looping, please refer to this post: When to use NSEnumerationConcurrent

Upvotes: 0

Devin
Devin

Reputation: 900

Check the documentation, NSDictionary can do this without enumeration.

NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:myObjects forKeys:myKeys];

If you're trying to add values to an existing mutableDictionary, it can do that too.

[mutableDictionary addEntriesFromDictionary:dictionary];

Upvotes: 5

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26048

I'd recommend using a regular for loop and just using object at index instead, or just make your own counter and do the same thing. But if you want to keep the foreach and don't want to make your own counter you could do this:

[self.myDict setObject:[myStrings objectAtIndex:[myKeys indexOfObject:key]] 
                forKey: key];

Upvotes: 0

Related Questions