从NSArray中选择一个随机objectAtIndex [英] selecting a random objectAtIndex from NSArray
问题描述
我有一个NSArray,其中包含索引0-9中的10个对象。数组中的每个条目都是引号。
当我的用户选择随机引用选项时,我希望能够从数组中选择一个随机条目并显示该条目中包含的文本。 / p>
有人能指出我如何实现这个目标吗?
我建议您使用此代替硬编码10;这样,如果您添加更多报价,它将自动完成,而无需您更改该数字。
NSInteger randomIndex = arc4random()%[array count];
NSString * quote = [array objectAtIndex:randomIndex];
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?
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.
NSInteger randomIndex = arc4random()%[array count];
NSString *quote = [array objectAtIndex:randomIndex];
这篇关于从NSArray中选择一个随机objectAtIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!