I have a use case where the application will automatically attempt to retrieve a location, the user can deny the permission, then the user can trigger the app to look for the location again (this time allowing it), but then the app will crash. Here's the basic code and use case steps, below, what am I doing wrong?
@interface AppViewController : UIViewController <CLL开发者_JAVA技巧ocationManagerDelegate>{
CLLocationManager *locationManager;
}
@property (retain,nonatomic) CLLocationManager *locationManager;
//... method declaration
@end
@implementation AppViewController
@synthesize locationManager;
-(void)MethodThatAutomaticallyGetsLocation{
[self FindLocation];
}
-(IBAction)UserTriggerToGetLocation{
[self FindLocation];
}
-(void)FindLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
// ... do some stuff
// ... save location info to core data object
[locationManager stopUpdatingLocation];
locationManager.delegate = nil;
[locationManager release];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
// ... conditionally display error message
// based on type and app state
[locationManager stopUpdatingLocation];
locationManager.delegate = nil;
[locationManager release];
}
- (void)dealloc {
// locationManager not released here, its released above
}
@end
- App loads view, messages
MethodThatAutomaticallyGetsLocation
FindLocation
is called to setuplocationManager
- Phone asks permission to share location
- User denies permission
locationManager:didFailWithError
is called, releaseslocationManager
- User interacts with UI, triggers
(IBAction) UserTriggerToGetLocation
which callsFindLocation
- Phone asks permission again, this time user allows it
locationManager:didUpdateToLocation:fromLocation
does its thing
Then the app crashes inside locationManager:didUpdateToLocation:fromLocation
when [locationManager release]
is called. Specifically I get EXC_BAD_ACCESS
which would imply locationManager
is released already? but where?
What did I do wrong?
Guh, nevermind. I think I am doing something wrong with releasing before dealloc
but I also realize I don't need to release before then. By simply stopping the locationManager in its response handlers, I can then restart it for step 6 by changing UserTriggerToGetLocation
to call [locationManager startUpdatingLocation]
NOT FindLocation
again.
精彩评论