In my iOS app I have a view that moves a UIImageView using the accelerometer. When I exit the view back to the main screen, the app crashes. I cannot figure out why. In the viewDidUnload method I have this:
[ball removeFromSuperview];
In the .h file:
@interface PlayShotguniPad : UIViewController <UIAccelerometerDelegate> {
// Declare IBOutlets for the moving fly
IBOutlet UIImageView *ball;
// Floats for the movement data
float valueX;
float valueY;
}
In the .m, I have this code to move the fly:
-(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 method:
[self awakeFromNib];
IS there anything I have to do, like releasing anything when leaving the view, to prevent the crashing?
You have to set the accelerometer delegate to nil in your dealloc, otherwise a selector of a view controller that no longer exists will be called.