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

我有一个大的NSArray名称,我需要从该数组中随机获得4个logging(名称),我该怎么做?

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

我做了一个名为NSArray+RandomSelection 。 只要将这个类别导入到一个项目中,然后就可以使用

 NSArray *things = ... ... NSArray *randomThings = [things randomSelectionWithCount:4]; 

这是实现:

NSArray+RandomSelection.h

 @interface NSArray (RandomSelection) - (NSArray *)randomSelectionWithCount:(NSUInteger)count; @end 

NSArray+RandomSelection.m

 @implementation NSArray (RandomSelection) - (NSArray *)randomSelectionWithCount:(NSUInteger)count { if ([self count] < count) { return nil; } else if ([self count] == count) { return self; } NSMutableSet* selection = [[NSMutableSet alloc] init]; while ([selection count] < count) { id randomObject = [self objectAtIndex: arc4random() % [self count]]; [selection addObject:randomObject]; } return [selection allObjects]; } @end 

如果你喜欢Swift框架 ,也有一些更方便的function,可以随时结账HandySwift 。 您可以通过Carthage将其添加到您的项目中然后像这样使用它:

 import HandySwift let names = ["Harry", "Hermione", "Ron", "Albus", "Severus"] names.sample() // => "Hermione" 

还有一个选项可以一次获得多个随机元素

 names.sample(size: 3) // => ["Ron", "Albus", "Harry"] 

我希望这有帮助!