我正在尝试用一副扑克牌填充我的 nsmutablearray。卡片对象有花色和等级。代码如下:
-(void)loadCardNumbers {
if(numDecks > 0)
{
//for each deck
for(int i = 1; i<= numDecks; i++)
{
//for each suit
for(int j = 1; j <= 4; j++)
{
//for each card 1-ace
for(int k = 1; k <= 13; k++)
{
//create card and add to shoe
Card *c = [[Card alloc]initWithSuit:j AndRank:k];
NSLog(@"%@", c);
[cards addObject:c];
}
}
}
}
和卡类:
@implementation Card
//return ace of spades, arbitrary card.
-(id)init
{
return [self initWithSuit:DIAMONDS AndRank:ACE];
}
-(id)initWithSuit:(int)s AndRank:(int)r
{
self = [super init];
if(self)
{
suit = s;
rank = r;
}
return self;
}
-(int)suit
{
return suit;
}
-(int)rank
{
return rank;
}
-(NSString *) description
{
return [NSString stringWithFormat:@"CARD WITH SUIT %d AND RANK %d", suit, rank];
}
@end
出于某种原因,NSLog 在该方法中看起来是正确的(正确打印 1...4 代表西装,1...13 代表排名)。但是,当我在方法完成后对数组调用 description 时,所有对象都会打印“suit 4 rank 13”,这意味着它们都指向我添加的最后一个对象。有想法该怎么解决这个吗?
编辑:正如 arkku 指出的,我的 ivars 被声明为类变量。忘记在 Card.h 中的 ivars 周围包含大括号