I have an array of keys/values…
NSArray *keysAndValues = @[@"1", @"one", @"2", @"two", @"3", @"three"];
What’s the simplest way to convert this to an NSDictionary so that it matches a dictionary that looks like…
NSDictionary *dict = @{@"1" : @"two", @"2" : @"two", @"3" : @"three"};
I have code that just cycles through the array and extracts the key/values, but I was wondering if there’s a cleaner way or any built in NSDictionary methods that I’m missing?
You’re not missing anything. There isn’t any really convenient way other than looping to do this. Of course any solution would be, at root, looping, but it would be nice if there were some more “filtering” or re-arranging abilities built in to
NSArray(/me coughs discreetly and looks at Python list comprehensions).There’s likely to be something useful in this vein in vikingosegundo’s arraytools on GitHub, or similar collection-manipulation extensions by others. There’s certainly no harm in writing your own category method to do this, though, like I said, there would have to be a loop somewhere in there.
Here’s my suggestion, for whatever that’s worth. Split the array by enumerating it:
Seems like there should be a better way to do this, such as with an
NSIndexSetandobjectsAtIndexes:, but there’s no convenient way to create an index set with a non-contiguous bunch of indexes.Something like this, e.g., would be nice:
With a helper function:
So that you can do this: