是否可以将CLLocationManager Delegate方法放在Singleton类中,而该类是NSObject的子类而不是UIViewController?我想这样做,因为我喜欢从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对象始终为null。 感谢
答案 0 :(得分:0)
是的,可以将它们放在NSObject
子类中,这可能是一个单例。我用的是:
@interface MyCLController : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
...
@end
虽然以防它不是单身人士。
答案 1 :(得分:0)
摆脱你的alloc函数。它没有必要,并且返回nil,这意味着在nil指针上调用此init调用:
sharedLocController = [[self alloc] init];