iphone - 在 objective-c 中改组数组

标签 iphone ios ipad nsmutablearray nsarray

<分区>

Possible Duplicate:
What’s the Best Way to Shuffle an NSMutableArray?

我为 iphone/iPad 开发应用程序。我想打乱存储在 NSArray 中的对象。有什么方法可以用 objective-c 实现吗?

最佳答案

向 NSMutableArray 添加类别,使用 code provided by Kristopher Johnson -

//  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
{

  static BOOL seeded = NO;
  if(!seeded)
  {
    seeded = YES;
    srandom(time(NULL));
  }

    NSUInteger count = [self 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 = (random() % nElements) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}

@end

关于iphone - 在 objective-c 中改组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659718/

相关文章:

iphone - 对于源代码控制,我有哪些替代方案,GIT 会这样做吗?

iphone - iOS 7 : How to change the status bar text color as white in one view controller and black in second view controller?

iphone - OpenGL ES 中的拉伸(stretch)绘图 - iOS

ios - 仅在 Firebase 调用完成后设置 Collection View 方法

ios - 设置 Core Plot 饼图图例项目的样式

javascript - 防止 iPad 中的悬停状态

iphone - 我的 iPad 应用程序会导致设备重启吗?

iphone - Cocos2d:CCLabelTTF调用函数?

ios - 如何使用 AV Audio 录制一段特定时间的音频

uitableview - 如何从 iPad(iOS 9 及更高版本)的 UITableView 中删除分隔符插入?