gpt4 book ai didi

objective-c - 打乱 NSMutableArray : calling the method

转载 作者:行者123 更新时间:2023-12-03 17:51:40 25 4
gpt4 key购买 nike

我是 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

但现在我不知道如何实现“随机播放”:

@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”时,这只会导致空白屏幕。非常感谢任何建议。

最佳答案

嗨,我在下面粘贴了几行代码,它将按照您想要的方式对 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方法中添加以下代码

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

关于objective-c - 打乱 NSMutableArray : calling the method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24696620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com