Question

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?

Was it helpful?

Solution

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];

OTHER TIPS

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];

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top