UIButton操作EXC_BAD_ACCESS ARC
我有一个滚动视图,并添加了一个带有图像标签和按钮的视图到滚动视图。我将操作添加到按钮,当我运行它时,一切看起来都很好,但是当我点击某个按钮时,应用程序与EXC_BAD_ACCESS一起崩溃。我正在使用ARC,因此不确定是否导致问题,但不应该。它似乎无法找到我的行动,就像从内存中释放出来的东西。这里是我的代码:UIButton操作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的解除分配对象(zombie)。 
什么对象是displayPacks
的一种方法?是否在displayPacks
返回后保留该对象?请记住,像UIButton
这样的控件不会而不是保留其目标,因此您需要其他操作。
displayPacks是UIViewController的一种方法。我正在使用ARC,并假设它在displayPacks返回后被保留。我没有意识到UIButton不会保留它们的目标,我过去做过类似的事情,就是没有使用ARC。我所要做的只是将图像,标签和按钮添加到滚动视图中,并让它响应触摸事件以查看用户选择了哪一个。 – Chevol
我还没有完全弄明白,但看起来像bottons由于某种原因不保留。我所做的防止这种问题是使用类属性NSMutableArray * my_buttons来保存临时按钮:
UIButton * aButton = [[UIButton alloc] init ...]; ... [my_buttons addObject:aButton];
当然,如果只有一个按钮,你可以使它成为一个类属性。无论如何避免使用它作为局部变量。但是,这只是一些解决方法,我不知道你如何在ARC环境中“保留”本地变量。
告诉我这个类的名字,以及这个类的对象是在哪里创建的? –
Inder此方法在UIViewController中,类名称为LevelPackViewController。这是在用户按下按钮(开始按钮)时从另一个视图创建的。 – Chevol
如果我将组件添加到视图而不是UIScrollView,它可以正常工作,但我显然不能滚动通过关卡包。然而,点击它们不会返回错误,因此它使我认为UIScrolView正在被释放,所以是对按钮和目标idk的引用。 – Chevol