开发者

Objective C: Deleting UIButtons (not just removeFromSuperview)

I'm making a game that involves buttons moving across the screen. When one button reaches the edge of the screen without being tapped, you lose a bar of health.

-(void) moveStickFig:(NSTimer *)timer {
UIButton *stick = (UIButton *)timer.userInfo;
CGPoint oldPosition = stick.center;
stick.center = CGPointMake(oldPosition.x + 1 , oldPosition.y);
if (oldPosition.x == 900) {
    [stick removeFromSuperview];
    healthCount--;
    NSLog(@"%d", healthCount);
     }
}

When you click on 开发者_Go百科a button it disapears using [btn removeFromSuperview] The problem with this is the button still exists and continues moving across the screen. Is there a way to delete it completely? I've tried [stick release] but for some reason it just causes the app to freeze


It looks like you're using a repeating timer to move the button. If you don't explicitly end that timer, the timer is going to keep running, and moving the button.

Normally when you send the removeFromSuperview message to something like a button, it would deallocate or "delete" that object. This is because when the button is added to the superview, the superview retains the button, giving it a retain count of 1, and when it's removed from the superview, it releases it, giving it a retain count of 0.

However, because the button is stored as the userInfo of the timer, the timer also retains the object giving it a retain count of 2, and after you remove it from the superview it still has a retain count of 1. If you simply send the release message to the button, it will lower the retain count to 0 and it will deallocate the button, but it won't stop the timer. The next time the timer runs, it will cause problems because you're trying to access deallocated memory.

What you really want to do is to invalidate the timer: [timer invalidate]. This will stop the timer, and the timer will send a release message to the button, causing the button to be deallocated.


NSTimer retains its userInfo, which is the button object in your case. You should kill the timer using [timer invalidate].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜