Reputation: 1195
I have a dictionary of objects that I would like to access in a random order. It doesn't have to be properly random but just have a good amount of variation.
The dictionary looks something like this like this:
'customer0' : '<Customer Object>'
'customer1' : 'inactive'
'customer2' : 'inactive'
'customer3' : 'inactive'
'customer4' : '<Customer Object>'
The key corresponds to a UI element that will be used to represent a customer in a game and basically I want them to not appear in the same order everytime.
Upvotes: 0
Views: 506
Reputation: 324
About random numbers read more here on stack. So if you have string keys, you can use smth like this:
NSString *key = [NSString stringWithFormat:@"customer%d", arc4random()%5];
<customer object> *customObj = [yourDictionary objectForKey:key];
Upvotes: 3
Reputation: 3876
In pseudocode:
Upvotes: 2
Reputation: 6028
I haven't tested this, but something along these lines should achieve what you're aiming for:
//create dictionary
NSDictionary *dictionary = [NSDictionary dictionary];
//gather set of keys from array of keys
NSSet *keys = [NSSet setWithArray:[dictionary allKeys]];
//gather random key
NSString *key = [keys anyObject];
//gather dictionary value with key
NSString *value = [dictionary objectForKey:key];
By creating an NSSet
from the NSArray
of dictionary keys, you can use anyObject
to gather an random key from the array.
There are surely other ways to achieve this but this is the most concise approach I can think of.
Upvotes: 0