Question

When I was using an NSArray, it was easy:

NSArray *array = ...
lastIndex = INT_MAX;
...
int randomIndex;
do {
  randomIndex = RANDOM_INT(0, [array count] - 1);
} while (randomIndex == lastIndex);
NSLog(@"%@", [array objectAtIndex:randomIndex]);
lastIndex = randomIndex;

I need to keep track of the lastIndex because I want the feeling of randomness. That is, I don't want to get the same element twice in a row. So it shouldn't be "true" randomness.

From what I can tell, NSDictionary doesn't have something like -objectAtIndex:. So how do I accomplish this?

Was it helpful?

Solution

You can get an array of keys with allKeys (undefined order) or keysSortedByValueUsingSelector (if you want sorting by value). One thing to keep in mind (regarding lastIndex) is that even with sorting, the same index may come to refer to a different key-value pair as the dictionary grows.

Either of these (but especially keysSortedByValueUsingSelector) will come with a performance penalty.

EDIT: Since the dictionary isn't mutable, you should just be able to call allKeys once, and then just pick random keys from that.

OTHER TIPS

You could use the code below:

- (YourObjectType *)getRandomObjectFromDictionary:(NSDictionary *)dictionary
{
    NSArray *keys = dictionary.allKeys;
    return dictionary[keys[arc4random_uniform((int)keys.count)]];
}

To make it more efficient, you can cache keys in an instance variable. Hope this helps.

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