Har*_*sad 10 iphone nsmutablearray nsarray ipad ios
我为iphone/iPad开发应用程序.我想要对存储在NSArray中的对象进行洗牌.有没有办法用objective-c来实现它?
Sau*_*abh 12
添加一个类别到NSMutableArray,代码由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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14080 次 |
| 最近记录: |