使用关闭按钮时objc_msgSend EXC_BAD_ACCESS

时间:2013-03-11 10:05:57

标签: ios objective-c xcode uiview uibutton

在我的项目中,我在右上角添加了一个关闭按钮,如下所示:

int closeBtnOffset = 10;
UIImage* closeBtnImg = [UIImage imageNamed:@"popupCloseBtn.png"];
UIButton* closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[closeBtn setImage:closeBtnImg forState:UIControlStateNormal];
[closeBtn setFrame:CGRectMake( background.frame.origin.x + background.frame.size.width - closeBtnImg.size.width - closeBtnOffset, 
                               background.frame.origin.y ,
                               closeBtnImg.size.width + closeBtnOffset, 
                               closeBtnImg.size.height + closeBtnOffset)];
[closeBtn addTarget:self action:@selector(closePopupWindow) forControlEvents:UIControlEventTouchUpInside];
[bigPanelView addSubview: closeBtn];

closePopupWindw方法如下所示:

-(void)closePopupWindow
{
    //remove the shade
    [[bigPanelView viewWithTag: kShadeViewTag] removeFromSuperview];
    [self performSelector:@selector(closePopupWindowAnimate) withObject:nil afterDelay:0.1];

}

构建成功但是当我单击closeBtn按钮时,程序会关闭此消息:http://i45.tinypic.com/ddndsl.png

我认为代码没有任何问题,因为我从另一个项目中复制它并且它在那里运行良好,但在另一个项目中它们没有使用ARC,我不确定这是不是问题。

修改

-(void)closePopupWindowAnimate
{

    //faux view
    __block UIView* fauxView = [[UIView alloc] initWithFrame: CGRectMake(10, 10, 200, 200)];
    [bgView addSubview: fauxView];

    //run the animation
    UIViewAnimationOptions options = UIViewAnimationOptionTransitionFlipFromLeft |
    UIViewAnimationOptionAllowUserInteraction    |
    UIViewAnimationOptionBeginFromCurrentState;

    //hold to the bigPanelView, because it'll be removed during the animation

    [UIView transitionFromView:bigPanelView toView:fauxView duration:0.5 options:options completion:^(BOOL finished) {

        //when popup is closed, remove all the views
        for (UIView* child in bigPanelView.subviews) {
            [child removeFromSuperview];
        }
        for (UIView* child in bgView.subviews) {
            [child removeFromSuperview];
        }

        [bgView removeFromSuperview];

    }];
}

2 个答案:

答案 0 :(得分:3)

您正在访问已经发布的对象,最好使用属性,并设置属性类型strong(使用ARC),这样它们就可以保留在内存中的位置你的观点是活跃的。

声明您的UIButton作为类属性,它将解决您的问题。您还应该看到您的按钮已添加到bigPanelView,并且您在调用方法closePopupWindowAnimate之前删除了此视图

答案 1 :(得分:0)

从快速看,我怀疑问题可能是closePopupWindow中的performSelector调用:该按钮由bigPanelView保留,但这是在第一行中发布的。这可能意味着“自我”'然后在调用performSelector之前释放。

作为一种风格问题,请避免使用视图标记:在某种父对象中为相关视图定义属性要好得多。这也使得更容易避免保留周期和早期版本,就像你在这里遇到的问题一样