本文介绍了如何随机化 NSMutableArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
iphone - nsarray/nsmutablearray - 以随机顺序重新排列
我有一个包含 20 个对象的 NSMutableArray.有什么办法可以像洗牌一样随机化他们的顺序.(按顺序我指的是它们在数组中的索引)
I have an NSMutableArray that contains 20 objects. Is there any way that I could randomize their order like when you shuffle a deck. (By order I mean their index in the array)
就像我有一个包含以下内容的数组:
Like if I had an array that contained:
- 苹果
- 橙色
- 梨形
- 香蕉
我怎样才能随机化顺序,以便我可以得到类似的东西:
How could I randomize the order so that I could get something like:
- 橙色
- 苹果
- 香蕉
- 梨形
推荐答案
以下是一些示例代码:遍历数组,并随机切换一个对象的位置.
Here's some sample code:Iterates through the array, and randomly switches an object's position with another.
for (int x = 0; x < [array count]; x++) {
int randInt = (arc4random() % ([array count] - x)) + x;
[array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
}
这篇关于如何随机化 NSMutableArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!