簡體   English   中英

CLLocationManager始終為null-代理實現是一個Singleton類(NSObject的子類而不是UIViewController的子類)

[英]CLLocationManager is always null -Delegate implementation is a Singleton Class (Subclass of NSObject instead of Subclass of UIViewController)

是否可以將CLLocationManager委托方法放在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。 謝謝

是的,可以將它們放在NSObject子類中,這可能是單例。 我使用類似:

@interface MyCLController : NSObject <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
}

...

@end

即使萬一不是單身人士。

擺脫您的alloc函數。 沒必要,它返回nil,這意味着此init調用正在nil指針上被調用:

sharedLocController = [[self alloc] init];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM