【问题标题】:Shuffling an NSMutable Array: calling the method改组 NSMutableArray:调用方法
【发布时间】:2014-07-11 11:26:00
【问题描述】:

我是 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”时,这只会影响一个空白屏幕。非常感谢任何建议。

【问题讨论】:

  • 这段代码甚至不应该编译。
  • 因此请求帮助。没有理由拒绝我的问题。
  • 你不是在洗牌。你应该投反对票。
  • 我想做什么很明显。这不是一个草率的问题。我知道这段代码无法编译——我正在努力让它正确。仅仅因为我离题很远——作为一个初学者——并不意味着我不应该问我的问题。
  • 实际上,我已经付出了很多努力来找出如何打乱我的图像数组。这是我最后的手段。正如我所说,我无法弄清楚如何实现“洗牌”方法。其他人尝试回答我的问题——他们理解。你只是高傲而已。也许你想禁止所有菜鸟?如果这样的事情冒犯了你,请带着你的自鸣得意继续前进,伙计。

标签: objective-c xcode cocoa nsmutablearray shuffle


【解决方案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"]];

// 在 Shuffle Method 中添加如下代码

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];
}

【讨论】:

    【解决方案2】:

    只需使用这个api来洗牌对象exchangeObjectAtIndex:withObjectAtIndex:参考这个how to shuffle object in NSMutableArray?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多