【问题标题】:CLLocationManager initializing, releasing, initializing and then releasing causes crash?CLLocationManager 初始化、释放、初始化再释放导致崩溃?
【发布时间】:2010-06-25 18:00:13
【问题描述】:

我有一个用例,应用程序将自动尝试检索位置,用户可以拒绝权限,然后用户可以触发应用程序再次查找位置(这次允许),但随后应用程序会崩溃。这是基本代码和用例步骤,下面,我做错了什么?

@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 release] 时,应用程序在locationManager:didUpdateToLocation:fromLocation 内部崩溃。具体来说,我得到EXC_BAD_ACCESS 这意味着locationManager 已经发布了?但在哪里?

我做错了什么?

【问题讨论】:

    标签: iphone cocoa-touch iphone-sdk-3.0 ios4


    【解决方案1】:

    嗯,没关系。我想我 amdealloc 之前发布有问题,但我也意识到我不需要在那之前发布。通过简单地在其响应处理程序中停止 locationManager,我可以通过将 UserTriggerToGetLocation 更改为再次调用 [locationManager startUpdatingLocation] 而不是 FindLocation 来重新启动它以进行第 6 步。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      相关资源
      最近更新 更多