我有一本我想以随机顺序访问的对象字典。它不必是适当的随机,而只是有大量的变化。
字典看起来像这样:
'customer0' : '<Customer Object>'
'customer1' : 'inactive'
'customer2' : 'inactive'
'customer3' : 'inactive'
'customer4' : '<Customer Object>'
该键对应于一个 UI 元素,该元素将用于代表游戏中的客户,基本上我希望它们不会每次都以相同的顺序出现。
我有一本我想以随机顺序访问的对象字典。它不必是适当的随机,而只是有大量的变化。
字典看起来像这样:
'customer0' : '<Customer Object>'
'customer1' : 'inactive'
'customer2' : 'inactive'
'customer3' : 'inactive'
'customer4' : '<Customer Object>'
该键对应于一个 UI 元素,该元素将用于代表游戏中的客户,基本上我希望它们不会每次都以相同的顺序出现。
关于随机数在 stack 上阅读更多信息。所以如果你有字符串键,你可以像这样使用 smth:
NSString *key = [NSString stringWithFormat:@"customer%d", arc4random()%5];
<customer object> *customObj = [yourDictionary objectForKey:key];
在伪代码中:
我没有对此进行测试,但是这些方面的东西应该可以实现您的目标:
//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];
通过NSSet从NSArray字典键中创建一个,您可以使用anyObject从数组中收集随机键。
当然还有其他方法可以实现这一点,但这是我能想到的最简洁的方法。