Re-arrange NSArray/MSMutableArray in random order

后端 未结 4 1444
余生分开走
余生分开走 2020-12-01 11:32

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?

4条回答
  •  我在风中等你
    2020-12-01 11:46

    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];
    }
    

提交回复
热议问题