目标C:每次点击按钮时,数组的值都会莫名其妙地重置

时间:2014-06-11 04:23:21

标签: ios objective-c uibutton nsmutablearray

我正在编写一个简单的iPhone应用程序来显示一副牌。每次放置一个按钮,都会显示一张新卡而无需更换。

每次调用我的buttonPressed方法时,持有卡片的deck类中的NSMutableArray都会重置为null。使用一些printf我发现当点击按钮时(即在前一个按钮点击的最后一行和新按钮点击的第一行之间)发生重置。此外,还没有创建新的Deck对象。

我认为touchCardButton中的任何一行都不会使得甲板上没有。我仍然可以在touchCardButton的最后一行画牌。但是,我无法在第一行画出它们。我认为有一些关于初始化我错过的套牌的事情(当我什么都不做的时候为什么会失去它的价值?)

重申一下,我并没有要求调试我的代码,因为我已经这样做了。我知道问题出现在touchCardButton的最后一行和第一行之间(表面上看,没有任何事情发生)。我想知道是什么原因导致这种情况发生,我也将代码作为参考。

- (IBAction)touchCardButton:(UIButton *)sender { //buttonClick Code
    PlayingCard *displayCard = nil;
    if(![self.deck drawRandom])
        printf("\nblank1\n");
    else printf("\nfull1\n");

    displayCard = [self.deck drawRandom];
    if(![self.deck drawRandom])
        printf("\nblank3\n");
    else printf("\nfull3\n");


    if (!displayCard) {
        if(![self.deck drawRandom])
            printf("\nblank4\n");
        else printf("\nfull4\n");

        printf("null cards");


        [sender setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [sender setTitle:@"" forState:UIControlStateNormal];
    }
    else{

        [sender setBackgroundImage:[UIImage imageNamed:@"front"] forState:UIControlStateNormal];
        [sender setTitle:[displayCard contents] forState:UIControlStateNormal];

    }
    self.flipCount++;

    if(![self.deck drawRandom])
        printf("\nblank5\n");
    else printf("\nfull5\n");
}

甲板代码

- (instancetype) init{

    self = [super init];
    printf ("remade");

    if (self){
        for (NSString *curSuit in [PlayingCard validSuits])
            for (NSString *curRank in [PlayingCard validRanks]) {
                PlayingCard *addedCard = [[PlayingCard alloc] init];
                addedCard.rank = curRank;
                addedCard.suit = curSuit;//curSuit;
                [self addCard: addedCard];
                //printf([addedCard.suit UTF8String]);
            }
        if (self.beenMade)
            printf("true");
        else
            printf("false");
    }
    self.beenMade = true;

    return self;
}

和抽奖卡方法

- (PlayingCard *) drawRandom {
    if(self.cards.count){
        printf("swag");
        unsigned index = arc4random()%self.cards.count;
        PlayingCard *cardDealt = self.cards[index];
        [self.cards removeObjectAtIndex: index];

        return cardDealt;
    }

    else
        return nil;

}

1 个答案:

答案 0 :(得分:1)

确保在deck类中为cards数组调用alloc,否则你将消息发送给nil对象。

- (instancetype) init{

    self = [super init];
    printf ("remade");

    if (self){
        self.cards = [[NSMutableArray alloc] init];
        // Rest of code 
    }


    return self;
}