CLLocationManager 始终为 null -Delegate 实现是单例类(NSObject 的子类而不是 UIViewController 的子类)
Posted
技术标签:
【中文标题】CLLocationManager 始终为 null -Delegate 实现是单例类(NSObject 的子类而不是 UIViewController 的子类)【英文标题】:CLLocationManager is always null -Delegate implementation is a Singleton Class (Subclass of NSObject instead of Subclass of UIViewController) 【发布时间】:2012-01-20 14:55:59 【问题描述】:是否可以将 CLLocationManager 委托方法放在作为 NSObject 的子类而不是 UIViewController 的 Singleton 类中?我想这样做,因为我想从 App Delegate 调用 Singleton 并在 UI 加载时开始获取坐标
我有一个 locationcontroller 类,其中有以下初始化代码
static locationController *sharedLocController = NULL;
+(locationController *) getSharedController
if (sharedLocController !=nil)
NSLog(@"locationController has already been created.....");
return sharedLocController;
@synchronized(self)
if (sharedLocController == nil)
sharedLocController = [[self alloc] init];
return sharedLocController;
//==============================================================================
+(id)alloc
@synchronized([locationController class])
NSAssert(sharedLocController == nil, @"Attempted to allocate a second instance of a sharedLocMgr singleton.");
sharedLocController = [super alloc];
return sharedLocController;
return nil;
//==============================================================================
-(id)init
self = [super init];
if(sharedLocController !=nil)
if(!self.locMgr)
[self initLocationManager];
return sharedLocController;
//==============================================================================
-(void)initLocationManager
self.locMgr = [[CLLocationManager alloc] init];
self.locMgr.delegate = self;
self.locMgr.distanceFilter = kCLDistanceFilterNone;
self.locMgr.desiredAccuracy = kCLLocationAccuracyBest;
[self.locMgr startUpdatingLocation];
NSLog(@"location manager object %@", locMgr);
问题是 self.locMgr 对象始终为空。 谢谢
【问题讨论】:
【参考方案1】:摆脱你的 alloc 函数。这不是必需的,它返回 nil,这意味着这个 init 调用被一个 nil 指针调用:
sharedLocController = [[self alloc] init];
【讨论】:
【参考方案2】:是的,可以将它们放在NSObject
子类中,这可能是一个单例。我使用类似的东西:
@interface MyCLController : NSObject <CLLocationManagerDelegate>
CLLocationManager *locationManager;
...
@end
虽然它不是单例。
【讨论】:
以上是关于CLLocationManager 始终为 null -Delegate 实现是单例类(NSObject 的子类而不是 UIViewController 的子类)的主要内容,如果未能解决你的问题,请参考以下文章
CLLocationManager 确保 iphone 的最佳准确性
应用程序再次激活时 CLLocationManager 的奇怪行为