在模型init上启动app时无限循环和访问错误

时间:2013-03-16 20:10:27

标签: ios

请帮助......我正在试图弄清楚这个问题。 我对iOS很陌生,所以如果它显而易见,请不要对我太过刻薄! ;)

我正在使用xcode 4.6并定位iPhone6.1模拟器。

启动我的应用时出现以下错误:

EXC_BAD_ACCESS code = 2

调试导航器中出现了一些线程,导致相信某处存在某种无限循环(我无法看到哪里)。

ViewController.m 中输入在PlayCtrollerDeck.m 中的(id)init 旁边出现错误:

Card *card = [self.deck drawRandonCard];


ViewConrtoller:

#import "ViewController.h"

#import "PlayingCardDeck.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *flipsLabel;
@property (nonatomic) int flipCount;
@property (strong, nonatomic) Deck *deck;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;

@end

@implementation ViewController

@synthesize deck = _deck;

- (IBAction)flipCard:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    self.flipCount++;
}

- (void)setFlipCount:(int)flipCount
{
    _flipCount = flipCount;
    self.flipsLabel.text = [NSString stringWithFormat:@"Flips: %d", self.flipCount];
}

- (Deck *)deck
{
    if (!_deck) _deck = [[PlayingCardDeck alloc] init];
    return _deck;
}

- (void)setCardButtons:(NSArray *)cardButtons
{
    _cardButtons = cardButtons;
    for (UIButton *cardButton in cardButtons)
    {
        Card *card = [self.deck drawRandonCard];
        [cardButton setTitle:card.contents forState:UIControlStateSelected];
    }
}

@end


Deck.m

#import "Deck.h"

@interface Deck()

@property (strong, nonatomic) NSMutableArray *cards;

@end


@implementation Deck

- (NSMutableArray *)cards
{
    if (!_cards) _cards = [[NSMutableArray alloc] init];
    return _cards;
}

- (void)addCard:(Card *)card atTop:(BOOL)atTop
{
    if (atTop)
    {
        [self.cards insertObject:card atIndex:0];
    }
    else
    {
        [self.cards addObject:card];
    }
}

- (Card *)drawRandonCard
{
    Card *randomCard = nil;

    if (self.cards.count)
    {
        unsigned index = arc4random() % self.cards.count;
        randomCard = self.cards[index];
        [self.cards removeObjectAtIndex:index];
    }

    return randomCard;
}

@end


PlayingCardDeck.m

#import "PlayingCardDeck.h"
#import "PlayingCard.h"

@implementation PlayingCardDeck

- (id)init
{
    self = [self init];

    if (self)
    {
        for (NSString *suit in [PlayingCard validSuits])
        {
            for (NSUInteger rank=1; rank <= [PlayingCard maxRank]; rank++)
            {
                PlayingCard *card = [[PlayingCard alloc] init];
                card.suit = suit;
                card.rank = rank;
                [self addCard:card atTop:YES];
            }
        }
    }

    return self;
}

@end

1 个答案:

答案 0 :(得分:4)

在PlayerCardDeck.m self = [self init]中应为self = [super init]。这导致无限循环。