有没有办法在NSDictionary中获取完全随机的密钥?
NSString *key = [enumeratorForKeysInDictionary nextObject];
我有这个代码以非随机方式迭代字典。
我应该将所有键添加到NSSet然后从那里随机拉出来吗?
有更有效的方法吗?
答案 0 :(得分:6)
见:
NSArray *array = [dictionary allKeys];
int random = arc4random()%[array count];
NSString *key = [array objectAtIndex:random];
答案 1 :(得分:3)
NSArray* allKeys = [dictionary allKeys];
id randomKey = allKeys[arc4random_uniform([allKeys count])];
id randomObject = dictionary[randomKey];
答案 2 :(得分:1)
你也可以尝试这样的事情:
NSArray* allKeys = [myDictionary allKeys];
然后你可以用方法rand()在上面的NSArray中获取一个随机索引来获取随机密钥。
答案 3 :(得分:1)
同样的想法,使用随机索引到键,但一些改进:(1)字典类别,(2)块枚举,像本机,(3)最重要 - 随机枚举,我们必须消除钥匙已经访问过。这将随机访问每个密钥,恰好一次(除非调用者在块中设置stop = YES):
//
// NSDictionary+RandBlockEnum.h
//
#import <Foundation/Foundation.h>
@interface NSDictionary (RandBlockEnum)
- (void)enumerateKeysAndObjectsRandomlyUsingBlock:(void (^)(id, id, BOOL *))block;
@end
//
// NSDictionary+RandBlockEnum.m
//
#import "NSDictionary+RandBlockEnum.h"
@implementation NSDictionary (RandBlockEnum)
- (void)enumerateKeysAndObjectsRandomlyUsingBlock:(void (^)(id, id, BOOL *))block {
NSMutableArray *keys = [NSMutableArray arrayWithArray:[self allKeys]];
BOOL stop = NO;;
while (keys.count && !stop) {
id randomKey = keys[arc4random_uniform(keys.count)];
block(randomKey, self[randomKey], &stop);
[keys removeObject:randomKey];
}
}
@end
这样称呼:
#import "NSDictionary+RandBlockEnum.h"
NSDictionary *dict = @{ @"k1" : @"o1", @"k2" : @"o2", @"k3" : @"o3" };
[dict enumerateKeysAndObjectsRandomlyUsingBlock:^(id key, id object, BOOL *stop) {
NSLog(@"%@, %@", key, object);
}];
答案 4 :(得分:1)
@ BestCoder的现代单行版答案:
Array(dictionary.keys)[Int(arc4random_uniform(UInt32(dictionary.keys.count)))]
src
答案 5 :(得分:0)
您可以创建一个集合,然后从集合中抓取任何对象。
NSSet *set = [NSSet setWithArray:[myDictionary allKeys]];
NSString *randomKey = [set anyObject];
答案 6 :(得分:0)
SWIFT 4
你有一本字典
Node
获取一个像这样的随机键值
let ads = _segueDataFromHomeToGuessMatch_NSType[Constants.Matches.ads] as! NSDictionary
像这样得到随机密钥的值
let rd_ad_key = ads.allKeys[Int(arc4random_uniform(UInt32(ads.count)))] as! String