I did a build and analyze and was warned about a potential leak of an object stored into ‘locationManager’. I was wondering how this should be handled properly. Here’s the code:
// Compass Code
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([CLLocationManager locationServicesEnabled] &&
[CLLocationManager headingAvailable]) {
[locationManager startUpdatingLocation];
[locationManager startUpdatingHeading];
locationManager.headingFilter = 2; // 2 degrees
} else {
NSLog(@"Can't report heading");
}
thanks for any help
On the first line you
allocthe location manager. This means you own that reference, and you should release it when you are done.You need to either release the location manager when you have finished setting it up:
Or autorelease it on the same line you alloc it:
Having said that, you should probably be storing the location manager in an instance variable so you can stop the location updates at some point. Otherwise
selfmight get deallocated and the location manager will continue sending messages to that deallocated object. This will cause a crash.After making an instance variable, your dealloc should probably have this:
Clearing the delegate will make sure the location manager will not send any messages to us once we have been deallocated. Then we stop the location updates and release the instance variable because we no longer need it.