2010-06-25 128 views
0

我有一個用例,其中應用程序會自動嘗試檢索一個位置,用戶可以拒絕該權限,然後用戶可以觸發應用程序再次查找該位置(這次允許它),但然後該應用程序將崩潰。以下是基本代碼和用例步驟,下面是我做錯了什麼?CLLocationManager初始化,釋放,初始化,然後釋放導致崩潰?

@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. 應用程序加載瀏覽,郵件MethodThatAutomaticallyGetsLocation
  2. FindLocation被稱爲設置locationManager
  3. 電話詢問權限共享位置
  4. 用戶拒絕允許
  5. locationManager:didFailWithError被調用時,釋放locationManager
  6. 用戶與UI交互,觸發(IBAction) UserTriggerToGetLocation這就要求FindLocation
  7. 電話又問許可,這時候用戶允許它
  8. locationManager:didUpdateToLocation:fromLocation就執行

然後應用程序崩潰內locationManager:didUpdateToLocation:fromLocation[locationManager release]被調用。具體來說,我得到EXC_BAD_ACCESS這意味着locationManager已經發布?但是哪裏?

我做錯了什麼?

回答

0

呃,沒關係。我想我amdealloc之前發佈時發生了一些問題,但我也意識到我不需要在此之前發佈。通過簡單地在其響應處理程序中停止locationManager,我可以通過將UserTriggerToGetLocation更改爲[locationManager startUpdatingLocation] NOT FindLocation來重新啓動它以執行步驟6。