How to select random key from NSDictionary?

When I used 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 track lastIndex because I need a sense of randomness. That is, I do not want to receive the same element twice in a row. Therefore, this should not be a “true” accident.

From what I can tell, NSDictionary does not have something like an AtIndex: object. So how can I do this?

+3
source share
2 answers

allKeys (undefined order) keysSortedByValueUsingSelector ( ). , ( lastIndex), , "-", .

( keysSortedByValueUsingSelector) .

EDIT: , allKeys , .

+2

:

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

, keys . .

+1

Source: https://habr.com/ru/post/1712344/


All Articles