当我使用 NSArray 时,这很简单:
NSArray *array = ...
lastIndex = INT_MAX;
...
int randomIndex;
do {
randomIndex = RANDOM_INT(0, [array count] - 1);
} while (randomIndex == lastIndex);
NSLog(@"%@", [array objectAtIndex:randomIndex]);
lastIndex = randomIndex;
我需要跟踪最后一个索引,因为我想要随机的感觉。也就是说,我不想连续两次获取相同的元素。所以它不应该是“真正的”随机性。
据我所知,NSDictionary 没有类似 -objectAtIndex: 的东西。那么我该如何实现这一点呢?
You can get an array of keys with allKeys http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDictionary/allKeys (undefined order) or keysSortedByValueUsingSelector http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/doc/uid/20000140-BABCJBAG (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.
其中任何一个(尤其是keySortedByValueUsingSelector)都会带来性能损失。
编辑:由于字典不可变,因此您应该只能调用 allKeys 一次,然后从中选择随机键。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)