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 co开发者_JAVA技巧de:
// 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 alloc
the 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:
// ...
locationManager.headingFilter = 2; // 2 degrees
[locationManager release];
Or autorelease it on the same line you alloc it:
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
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 self
might 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:
- (void)dealloc
{
// ...
locationManager.delegate = nil;
[locationManager stopUpdatingLocation];
[locationManager release];
// ...
[super dealloc];
}
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.
Manually releasing the variables might be risky sometimes. We don't know where exactly to release the variables. One thing we can do to avoid the manual work of releasing the variables is click on the project in Build setting search for automatic reference counting set the value of it to "YES". By setting the value to "YES" no need to release the variables manually.
精彩评论