UIButton操作EXC_BAD_ACCESS ARC

时间:2011-11-02 06:26:15

标签: objective-c cocoa-touch uibutton automatic-ref-counting

我有一个scrollview,并且正在向scrollview添加带有图像标签和按钮的视图。我将操作添加到按钮,当我运行它时一切看起来都很好但是当我点击一个按钮时,应用程序崩溃了EXC_BAD_ACCESS。我正在使用ARC,所以不确定是否会导致问题,但不应该。似乎无法找到我的行为,就像从记忆中释放出来的东西一样。这是我的代码:

-(void)lvlSelected:(id)sender{
    NSLog(@"Selected level pack");
}

/*
 DISPLPAYPACKS
 This will take the loaded level packs and display them in the scroll view for selection
 */

-(void)displayPacks{
    //Iterate thru the installed level packs and load some tiles they can select
    for (int i = 0; i < installedLevelPacks.count; i++){ 
        levelPack *curPack = [installedLevelPacks objectAtIndex:i];
        CGFloat x = i * 110; 
        //Add the view to contain the rest of our elements
        UIView *tileView = [[UIView alloc] initWithFrame:CGRectMake(x, 0, 100, 125)]; 
        //view.backgroundColor = [UIColor greenColor]; 
        //Add a label to the bottom to hold the title
        UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, tileView.frame.origin.y+100, 100, 25)];
        titleLbl.textAlignment=UITextAlignmentCenter;
        titleLbl.font=[UIFont fontWithName:@"American Typewriter" size:12];
        titleLbl.adjustsFontSizeToFitWidth=YES;
        titleLbl.text=curPack.title;
        //Add the preview image to the tile
        UIImageView *previewImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:curPack.previewImg]];
        previewImg.frame=CGRectMake(0, 0, 100, 100);
        //Add the button over the tile
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
        aButton.frame = CGRectMake(0, 0, 100, 125);
        //Set the tag to the level ID so we can get the pack later
        [aButton setTag:i];
        [aButton setTitle:curPack.title forState:UIControlStateNormal];
        [aButton addTarget:self action:@selector(lvlSelected:) forControlEvents:UIControlEventTouchUpInside];

        [tileView addSubview:previewImg];
        [tileView addSubview:titleLbl];
        [tileView addSubview:aButton];
        [lvlScroller addSubview:tileView]; 
    }
    //Set the total size for the scrollable content
    lvlScroller.contentSize = CGSizeMake(installedLevelPacks.count*110, 125); 
}

我真的在这里遗漏了一些东西,我之前做过这件事而不是ARC,所以这就是为什么我被困在那个罪魁祸首。

NSZombie输出状态: Objective-C消息被发送到地址为0x6b8d530的解除分配对象(僵尸)。 

2 个答案:

答案 0 :(得分:1)

displayPacks什么对象是一种方法? displayPacks返回后是否保留该对象?请注意,UIButton之类的控件会保留其目标,因此您还需要其他操作。

答案 1 :(得分:1)

我还没有完全弄清楚,但看起来因为某种原因不会保留掉。我为防止此类问题所做的是使用类属性NSMutableArray * my_buttons来保存临时按钮:

UIButton * aButton = [[UIButton alloc] init ...]; ... [my_buttons addObject:aButton];

当然,如果只有一个按钮,你可以把它变成一个类属性。无论如何,避免将其用作局部变量。但同样,这只是一些解决方法,我真的不知道你如何在ARC环境中“保留”局部变量。