如何随机化 NSMutableArray? [英] How to randomize an NSMutableArray?

查看:78
本文介绍了如何随机化 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:

  1. 苹果
  2. 橙色
  3. 梨形
  4. 香蕉

我怎样才能随机化顺序,以便我可以得到类似的东西:

How could I randomize the order so that I could get something like:

  1. 橙色
  2. 苹果
  3. 香蕉
  4. 梨形

推荐答案

以下是一些示例代码:遍历数组,并随机切换一个对象的位置.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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