改组NSMutableArray:调用方法

时间:2014-07-11 11:26:00

标签: objective-c xcode cocoa nsmutablearray shuffle

我是Objective-C的新手,通过反复试验来学习!如果这个问题有些天真,请原谅我。

我已经创建了一系列图像,需要对它们进行随机播放。我已经使用了这里给出的建议:

What's the Best Way to Shuffle an NSMutableArray?

现在我需要实现方法'shuffle'。我的数组及其实现有单独的类别:

@interface theKid : NSObject {
    NSMutableArray* _cards;
}

@property(strong, nonatomic, readonly) NSMutableArray *cards;

- (UIImage*) shuffledCard;

@end

但现在我无法弄清楚如何实施'shuffle':

@implementation theKid

- (NSMutableArray *) cards {

    _cards = [[NSMutableArray alloc] initWithObjects:
          [UIImage imageNamed:@"One"],
          [UIImage imageNamed:@"Two"],
          [UIImage imageNamed:@"Three"],
          [UIImage imageNamed:@"Four"], nil];

    return _cards;

}

- (UIImage*) shuffledCard {
    shuffle *cards;

    return [cards objectAtIndex:0];
}

@end

当我尝试调用'shuffledCard'时,这只会影响一个空白屏幕。任何建议都非常感激。

2 个答案:

答案 0 :(得分:1)

您好我已经粘贴了几行代码,这些代码将完全像您想要的那样随机播放一个NSMutable数组。

NSMutableArray *  _cards = [[NSMutableArray alloc] init];
[_cards addObject:[UIImage imageNamed:@"One.png"]];
[_cards addObject:[UIImage imageNamed:@"Two.png"]];
[_cards addObject:[UIImage imageNamed:@"Three.png"]];
[_cards addObject:[UIImage imageNamed:@"Four.png"]];
[_cards addObject:[UIImage imageNamed:@"Five.png"]];

//在随机播放方法中添加以下代码

NSUInteger count = [_cards count];
for (NSUInteger i = 0; i < count; ++i)
{
    NSInteger remainingCount = count - i;
    int exchangeIndex = i + arc4random_uniform(remainingCount);
    [_cards exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
    UIImage * image = [_cards objectAtIndex:i];
}

答案 1 :(得分:0)

只需使用此API来移动对象exchangeObjectAtIndex:withObjectAtIndex:请参阅此how to shuffle object in NSMutableArray?