What's the Best Way to Shuffle an NSMutableArray?

后端 未结 12 1691
太阳男子
太阳男子 2020-11-21 11:53

If you have an NSMutableArray, how do you shuffle the elements randomly?

(I have my own answer for this, which is posted below, but I\'m new to Cocoa an

12条回答
  •  梦如初夏
    2020-11-21 12:09

    Edit: This is not correct. For reference purposes, I did not delete this post. See comments on the reason why this approach is not correct.

    Simple code here:

    - (NSArray *)shuffledArray:(NSArray *)array
    {
        return [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            if (arc4random() % 2) {
                return NSOrderedAscending;
            } else {
                return NSOrderedDescending;
            }
        }];
    }
    

提交回复
热议问题