什么是最好的方式来洗牌一个NSMutableArray?如果你有NSMutableArray如何随机调整元素?(我有我自己的答案,这是在下面,但我是新的可可,我有兴趣知道是否有更好的方法。)更新:截至iOS 10+和MacOS 10.12+,有一个-[NSMutableArray shuffledArray]方法,可用于洗牌。看见https:/developer.apple.com/Document/Foundation/nsArray/1640855-Shuffledarray?language=objc关于细节。(但请注意,这将创建一个新的数组,而不是对现有的元素进行洗牌。)
3 回答
潇潇雨雨
TA贡献1833条经验 获得超4个赞
编辑:
编辑:(arc4random() % nElements)
arc4random_uniform(nElements)
编辑:
编辑:
// NSMutableArray_Shuffling.h#if TARGET_OS_IPHONE#import <UIKit/UIKit.h>#else#include <Cocoa/Cocoa.h>#endif // This category enhances NSMutableArray by providing // methods to randomly shuffle the elements.@interface NSMutableArray (Shuffling)- (void)shuffle;@end // NSMutableArray_Shuffling.m#import "NSMutableArray_Shuffling.h"@implementation NSMutableArray (Shuffling)- (void)shuffle{ NSUInteger count = [self count]; if (count <= 1) return; for (NSUInteger i = 0; i < count - 1; ++i) { NSInteger remainingCount = count - i; NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount); [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex]; }}@end
- 3 回答
- 0 关注
- 511 浏览
添加回答
举报
0/150
提交
取消