Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using NSArray/NSMutable array to store different objects. Once all the objects are added, I want to re-arrange them in random order. How can I do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
515 views
Welcome To Ask or Share your Answers For Others

1 Answer

NSUInteger count = [yourMutableArray count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
   int nElements = count - i;
   int n = (arc4random() % nElements) + i;
   [yourMutableArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...