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? 回答1: #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--; } } } 回答2: I made a caregory called NSArray+RandomSelection . Just import this