请帮忙....我正在努力解决这个问题。 我是 iOS 的新手,所以如果这很明显,请不要对我太苛刻! ;)
我正在使用 xcode 4.6 并以 iPhone6.1 模拟器为目标。
启动我的应用程序时出现以下错误:
EXC_BAD_ACCESS code = 2
Debug Navigator 中出现了数百个线程,这导致人们相信某处存在某种无限循环(我只是看不到哪里)。
错误发生在 PlayingCardDeck.m 中的 (id)init 旁边,在从 ViewController.m 进入后,在行:
Card *card = [self.deck drawRandonCard];
查看 Controller :
#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
甲板.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
最佳答案
在 PlayerCardDeck.m 中 self = [self init]
应该是 self = [super init]
。这导致了无限循环。
关于ios - 模型初始化时应用程序启动时出现无限循环和访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15454179/