【问题标题】:selecting a random objectAtIndex from NSArray从 NSArray 中选择一个随机 objectAtIndex
【发布时间】:2011-10-29 16:44:24
【问题描述】:

我有一个 NSArray,它包含从索引 0 到 9 的 10 个对象。数组中的每个条目都是一个引号。

当我的用户选择“随机引用”选项时,我希望能够从数组中选择一个随机条目并显示该条目中包含的文本。

谁能指出我如何实现这一目标的正确方向?

【问题讨论】:

标签: iphone objective-c xcode ios4 nsarray


【解决方案1】:

我建议您使用它而不是硬编码 10;这样,如果您添加更多报价,它将自动解决,而无需您更改该数字。

NSInteger randomIndex = arc4random()%[array count];
NSString *quote = [array objectAtIndex:randomIndex];

【讨论】:

  • 太棒了!非常感谢!
【解决方案2】:

您可能想要使用 arc4random() 从 0-9 中挑选一个对象。然后,简单地做

NSString* string = [array objectAtIndex:randomPicked];

获取条目的文本。

【讨论】:

  • 完美。我设法使用 arc4random() 获得了随机数,但在提取文本时遇到了问题。谢谢。
【解决方案3】:

您可以使用arc4random()%10 获取索引。有一点偏差,应该不是问题。

最好还是使用arc4random_uniform(10),没有偏见,更容易使用。

【讨论】:

  • 嘿,我以为你有安全背景! arc4random_uniform 没有偏见,应该在这里使用。
  • 对,arc4random_uniform() 是正确使用的函数。我确实提到了轻微的偏见,对于 mod 10,偏见是微不足道的。我添加了一个更正附录。
【解决方案4】:

首先,在您的范围内获取一个随机数,请参阅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];
}

【讨论】:

  • 最好使用 arc4random()。如果没有提供种子,则每次运行应用都会返回 sam 序列。
  • @CocoaFu 首先,这就是我链接讨论并参考手册页的原因,并在代码示例中指出了变量随机方法。其次,你有没有试过每次都用不同的种子来调试程序?
  • 直到您对这部分进行了彻底的调试和工作,是的。当它与一个流一起工作时,你可以去尝试其他的。无论如何,发财并不需要加密级别的随机性。客户不会记录一百万个选择并抱怨 1/1,000,000 的偏差。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 2012-02-21
  • 2016-03-03
  • 2011-02-28
  • 2019-11-23
  • 1970-01-01
  • 2010-12-10
相关资源
最近更新 更多