Tun*_*vel 11 random objective-c nsarray ios
我有一个大的NSArray名称,我需要从该数组中随机获得4条记录(名称),我该怎么做?
Jul*_*rgé 21
#include <stdlib.h>
NSArray* names = ...;
NSMutableArray* pickedNames = [NSMutableArray new];
int remaining = 4;
if (names.count >= remaining) {
while (remaining > 0) {
id name = names[arc4random_uniform(names.count)];
if (![pickedNames containsObject:name]) {
[pickedNames addObject:name];
remaining--;
}
}
}
Run Code Online (Sandbox Code Playgroud)