2012-01-20 47 views
0

可以將CLLocationManager委託方法放在Singleton類中,該類是NSObject的子類而不是UIViewController?我想這樣做,因爲我還想從App委託調用辛格爾頓並開始獲取座標,而UI加載CLLocationManager始終爲空-Delegate實現是Singleton類(NSObject的子類而不是UIViewController的子類)

我有一個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對象始終爲空。 謝謝

回答

0

擺脫你的alloc函數。這是沒有必要,並返回nil,這意味着這個初始化調用獲取調用一個零指針:

sharedLocController = [[self alloc] init]; 
+0

感謝您的幫助 – banditKing

0

是的,把它們放在一個NSObject子類中是可以的,這可能是一個單身人士。我使用類似的東西:

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

... 

@end 

儘管萬一它不是一個單身人士。

相關問題