【发布时间】:2011-10-29 16:44:24
【问题描述】:
我有一个 NSArray,它包含从索引 0 到 9 的 10 个对象。数组中的每个条目都是一个引号。
当我的用户选择“随机引用”选项时,我希望能够从数组中选择一个随机条目并显示该条目中包含的文本。
谁能指出我如何实现这一目标的正确方向?
【问题讨论】:
标签: iphone objective-c xcode ios4 nsarray
我有一个 NSArray,它包含从索引 0 到 9 的 10 个对象。数组中的每个条目都是一个引号。
当我的用户选择“随机引用”选项时,我希望能够从数组中选择一个随机条目并显示该条目中包含的文本。
谁能指出我如何实现这一目标的正确方向?
【问题讨论】:
标签: iphone objective-c xcode ios4 nsarray
我建议您使用它而不是硬编码 10;这样,如果您添加更多报价,它将自动解决,而无需您更改该数字。
NSInteger randomIndex = arc4random()%[array count];
NSString *quote = [array objectAtIndex:randomIndex];
【讨论】:
您可能想要使用 arc4random() 从 0-9 中挑选一个对象。然后,简单地做
NSString* string = [array objectAtIndex:randomPicked];
获取条目的文本。
【讨论】:
您可以使用arc4random()%10 获取索引。有一点偏差,应该不是问题。
最好还是使用arc4random_uniform(10),没有偏见,更容易使用。
【讨论】:
arc4random_uniform 没有偏见,应该在这里使用。
arc4random_uniform() 是正确使用的函数。我确实提到了轻微的偏见,对于 mod 10,偏见是微不足道的。我添加了一个更正附录。
首先,在您的范围内获取一个随机数,请参阅this discussion 和相关的手册页。然后用它索引到数组中。
int random_number = rand()%10; // Or whatever other method.
return [quote_array objectAtIndex:random_number];
编辑:对于那些无法从链接中正确插入或只是不关心阅读建议的参考资料的人,让我为您说明这一点:
// Somewhere it'll be included when necessary,
// probably the header for whatever uses it most.
#ifdef DEBUG
#define RAND(N) (rand()%N)
#else
#define RAND(N) (arc4random()%N)
#endif
...
// Somewhere it'll be called before RAND(),
// either appDidLaunch:... in your application delegate
// or the init method of whatever needs it.
#ifdef DEBUG
// Use the same seed for debugging
// or you can get errors you have a hard time reproducing.
srand(42);
#else
// Don't seed arc4random()
#endif
....
// Wherever you need this.
NSString *getRandomString(NSArray *array) {
#ifdef DEBUG
// I highly suggest this,
// but if you don't want to put it in you don't have to.
assert(array != nil);
#endif
int index = RAND([array count]);
return [array objectAtIndex:index];
}
【讨论】: