views:

20

answers:

1

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 <CLLocationManagerDelegate>{  
    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
  1. App loads view, messages MethodThatAutomaticallyGetsLocation
  2. FindLocation is called to setup locationManager
  3. Phone asks permission to share location
  4. User denies permission
  5. locationManager:didFailWithError is called, releases locationManager
  6. User interacts with UI, triggers (IBAction) UserTriggerToGetLocation which calls FindLocation
  7. Phone asks permission again, this time user allows it
  8. 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?

A: 

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.

Jeof