从 NSArray 中随机选择一个 objectAtIndex
我有一个 NSArray,其中包含索引 0 - 9 的 10 个对象。数组中的每个条目都是一个引号。
当我的用户选择“随机引用”选项时,我希望能够从数组中选择一个随机条目并显示该条目中包含的文本。
谁能指出我如何实现这一目标的正确方向?
I have an NSArray which contains 10 objects from index 0 - 9. Each entry in the array is a quotation.
When my user selects the 'random quote' option I want to be able to select a random entry from the array and display the text that is contained in that entry.
Can anyone point me in the right direction on how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议您使用它而不是硬编码 10;这样,如果您添加更多报价,它会自动计算出来,而无需更改该数字。
I'd recommend you use this instead of hardcoding the 10; that way, if you add more quotations, it will work it out automatically, without you needing to change that number.
您可能想要使用 arc4random() 从 0-9 中选择一个对象。然后,只需
获取条目的文本即可。
Your probably going to want to use arc4random() to pick an object from 0-9. Then, simply do
to get the text of the entry.
您可以使用
arc4random()%10
来获取索引。存在轻微的偏差,这应该不是问题。最好使用
arc4random_uniform(10)
,没有偏差,而且更容易使用。You can use
arc4random()%10
to get an index. There is a slight bias that should not be a problem.Better yet use
arc4random_uniform(10)
, there is no bias and is even easier to use.首先,在边界之间获取一个随机数,请参阅 此讨论 和相关的手册页。然后用它索引到数组中。
编辑:对于那些无法从链接正确插入或只是不想阅读建议参考文献的人,让我为您说明一下:
First, get a random number between your bounds, see this discussion and the relevant man pages. Then just index into the array with it.
Edit: for those who can't properly interpolate from the links or just don't care to read suggested references, let me spell this out for you: