我有一个很大的NSArray名字,我需要从该数组中随机获得4条记录(名称),我该怎么做?
答案 0 :(得分: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--;
}
}
}
答案 1 :(得分:2)
我创建了一个名为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
答案 2 :(得分:2)
如果您更喜欢 Swift框架,还有一些更方便的功能,请随时查看 HandySwift 。您可以将它添加到项目 via Carthage ,然后像这样使用它:
import HandySwift
let names = ["Harry", "Hermione", "Ron", "Albus", "Severus"]
names.sample() // => "Hermione"
还可以选择一次多个随机元素:
names.sample(size: 3) // => ["Ron", "Albus", "Harry"]
我希望这有帮助!