在 NSArray 中选择一个随机对象 [英] Picking a Random Object in an NSArray

查看:29
本文介绍了在 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;

修改:

  • rand()random() 上使用 arc4random() 更简单,因为它不需要播种(调用 srand()srandom()).
  • 模运算符 (%) 使整个语句更短,同时也让它在语义上更清晰.
  • 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.

这篇关于在 NSArray 中选择一个随机对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆