【发布时间】:2011-04-30 05:53:43
【问题描述】:
我有一个很大的 NSArray 名称,我需要从该数组中随机获取 4 条记录(名称),我该怎么做?
【问题讨论】:
标签: objective-c ios random nsarray
我有一个很大的 NSArray 名称,我需要从该数组中随机获取 4 条记录(名称),我该怎么做?
【问题讨论】:
标签: objective-c ios random nsarray
#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
【讨论】:
if ([self count] < count) { count = [self count]; }
如果您更喜欢 Swift 框架,它还具有一些更方便的功能,请随时查看 HandySwift。您可以通过 Carthage 将其添加到您的项目中,然后像这样使用它:
import HandySwift
let names = ["Harry", "Hermione", "Ron", "Albus", "Severus"]
names.sample() // => "Hermione"
还有一个选项可以一次获取多个随机元素:
names.sample(size: 3) // => ["Ron", "Albus", "Harry"]
我希望这会有所帮助!
【讨论】: