本文介绍了在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() over rand() and random() is simpler because it does not require seeding (calling srand() or srandom()).
  • The modulo operator (%) makes the overall statement shorter, while also making it semantically clearer.
  • theArray.count is wrong. It will work, but count is not declared as a @property on NSArray, 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中选择随机对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 19:55