从nsarray获取n个随机对象(例如4)

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)

  • 是的,我刚刚用arc4random()取代了rand(),这是优越的,不需要播种. (3认同)