从NSMutableArray添加子视图后程序崩溃

时间:2013-06-17 23:29:06

标签: ios objective-c uiview nsmutablearray

现在我有一个UIView,上面有两个子视图。我正在尝试从定制的Card类向其中一个视图添加另一个子视图。问题是子视图来自NSMutableArray,每次我尝试将它添加到任何视图时它都会使程序崩溃。我知道这个问题与NSMutableArray有关,因为如果我只是尝试添加一个刚刚初始化的Card实例,就没有任何问题。有什么问题?

以下是代码:

初始化主视图发生这种情况:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        mainMenu = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        mainMenu.frame = CGRectMake(10, 944, 100, 50);
        [mainMenu setTitle:@"Main Menu" forState:UIControlStateNormal];
        [mainMenu addTarget:self action:@selector(goMainMenu) forControlEvents:UIControlEventTouchUpInside];

        reader = [[Reader alloc] init];
        deck = [reader getDeck];

        hand = [[Hand alloc] initWithFrame:CGRectMake(0, 1024/3, 768, 2048/3)];

        board = [[Board alloc] initWithFrame:CGRectMake(0, 0, 768, 1024/3)];
    }
    return self;
}

应该添加卡的方法:

- (void)viewDidLoad
{
    [super viewDidLoad];

    Card* card = [deck objectAtIndex:0];

    [hand addSubview:card];
    [self.view addSubview:hand];
    [self.view addSubview:board];
    [self.view addSubview:mainMenu];
}

这里是getDeck类中Reader方法的位置:

-(NSMutableArray*)getDeck {

    NSMutableArray* deck = [NSMutableArray arrayWithCapacity:72];

    Card* card;

    NSMutableArray* strings = [[scanner string] componentsSeparatedByString:@"\n"];

    while ([strings count] > 0) {

        [strings removeObjectAtIndex:0];

        card = [Card cardWithExpressions:[strings subarrayWithRange:NSMakeRange(0, 4)]];
        card.frame = CGRectMake(0, 0, 180, 252);

        [card setCoefficient:[self getCoefficientFromExpression:[card getPolynomial]]];

        [deck addObject:card];

        [strings removeObjectsInRange:NSMakeRange(0, 4)];
    }

    return deck;
}

1 个答案:

答案 0 :(得分:0)

解决。事实证明,我用于card的初始值设定项cardWithExpressions:,其中没有[super initWithFrame:]。把它放在那里,现在一切正常。