Tunyk Pavel Tunyk Pavel - 5 months ago 14
Objective-C Question

Get n random objects (for example 4) from nsarray

I have a large NSArray of names, I need to get random 4 records (names) from that array, how can I do that?

Answer
#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--;
       }
    }
}