使用加速度计退出视图时崩溃

时间:2012-09-23 07:57:39

标签: iphone objective-c ios xcode ipad

在我的iOS应用程序中,我有一个使用加速度计移动UIImageView的视图。当我将视图退出到主屏幕时,应用程序崩溃了。我无法弄清楚为什么。在viewDidUnload方法中,我有这个:

[ball removeFromSuperview];

在.h文件中:

@interface PlayShotguniPad : UIViewController  <UIAccelerometerDelegate> {

// Declare IBOutlets for the moving fly
IBOutlet UIImageView *ball;

// Floats for the movement data
float valueX;
float valueY;

}

在.m中,我有这个代码来移动苍蝇:

-(void)awakeFromNib {
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0/100.0];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
}

// Get accelerometer movement data, move fly with device tilt
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
valueX = acceleration.x*60.0;
valueY = acceleration.y*60.0;

int newX = (int)(ball.center.x +valueY);
if (newX > 1000-BALL_RADIUS)
    newX = 1000-BALL_RADIUS;
if (newX < 0+BALL_RADIUS)
    newX = 0+BALL_RADIUS;

int newY = (int)(ball.center.y +valueX);
if (newY > 740-BALL_RADIUS)
    newY = 740-BALL_RADIUS;
if (newY < 0+BALL_RADIUS)
    newY = 0+BALL_RADIUS;

CGPoint newCenter = CGPointMake(newX, newY);

ball.center = newCenter ;

}

viewDidLoad方法:

[self awakeFromNib];

我有什么必须做的,比如在离开视图时释放任何东西,以防止崩溃?

1 个答案:

答案 0 :(得分:1)

您必须在dealloc中将加速度计委托设置为nil,否则将调用不再存在的视图控制器的选择器。

- (void)dealloc {
[[UIAccelerometer sharedAccelerometer] setDelegate:nil];
}