在NSArray中选择随机对象 [英] Picking a Random Object in an NSArray
本文介绍了在NSArray中选择随机对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个对象数组, 1,2,3和4。
如何从这个数组中选择一个随机对象?
Say I have an array with objects, 1, 2, 3 and 4. How would I pick a random object from this array?
推荐答案
@ Darryl的回答是正确的,但可以使用一些细微的调整:
@Darryl's answer is correct, but could use some minor tweaks:
NSUInteger randomIndex = arc4random() % [theArray count];
修改:
- 使用
arc4random()
过rand()
和random()更简单,因为它不需要种子(调用
srand()
或srandom()
)。 / li>
- 取模运算符(
%)使总体语句更短,同时使其语义更清晰。
theArray.count
错误。它会工作,但count
未声明为@property
在NSArray
,因此应该通过点语法调用不。它的工作原理就是编译器如何解释点语法的副作用。
- 取模运算符(
- Using
arc4random()
overrand()
andrandom()
is simpler because it does not require seeding (callingsrand()
orsrandom()
). - The modulo operator (
%
) makes the overall statement shorter, while also making it semantically clearer. theArray.count
is wrong. It will work, butcount
is not declared as a@property
onNSArray
, and should therefore not be invoked via dot syntax. That it works is simply a side-effect of how dot syntax is interpreted by the compiler.
这篇关于在NSArray中选择随机对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文