3

我對iOS開發(我的第一個應用程序)很新,我遇到了這個問題。使用CLLocationManager的自定義位置管理器類

我有一個iPhone應用程序,應該在用戶按鈕觸摸時在多個ViewControllers中獲取用戶的當前位置。爲了防止冗餘代碼(執行locationManager:didFailWithErrorlocationManager:didUpdateToLocation:fromLocation等不同視圖控制器多次)我決定創建稱爲LocationManager的自定義類:

LocationManager.h

@interface LocationManager : NSObject <CLLocationManagerDelegate> { 
@private 
    CLLocationManager *CLLocationManagerInstance; 
    id<LocationManagerAssigneeProtocol> assignee; 
} 

-(void) getUserLocationWithDelegate:(id) delegate; 

LocationManager.m我有一個協議叫LocationManagerAssigneeProtocol我ViewControllers實現

@protocol LocationManagerAssigneeProtocol <NSObject> 

@required 
-(void) didUpdateToLocation:(CLLocation *) location; 

@end 

,在我的ViewController在需要的地方

- (IBAction)getMyLocation:(id)sender { 

    [locationMgr getUserLocationWithDelegate:self]; 
} 

此代碼的工作完美,但是,我有我在這裏,違反了一些設計模式,通過讓LocationManager的感覺能夠調用自己啓動對位置管理器調用的類的功能。另一方面,我不希望執行CLLocationManagerDelegate爲所有我應該與地點工作的視圖控制器。

這個問題有沒有更好的解決辦法?

+0

我不確定我關注「讓LocationManager能夠調用自己發起呼叫的類的功能」。如果我沒有弄錯,你使用委託協議來做這件事,這是可取的。 –

+0

我認爲這很好,這就是委派的工作原理,儘管只有協議上沒有依賴類。我建議的唯一的事情是,如果您擁有多個視圖控制器(取決於位置更新的相同實例),也許您可​​能想切換到基於通知的系統。 –

+0

@CarlVeazey請給我們舉一個例子,說明你會改變什麼來使它成爲通知的基礎? –

回答

2

我同意@CarlVeazey在這一個。代表非常適合在任何時候存在1對1關係,但在您的情況下,似乎您可能需要多個viewController來在任何給定時間響應位置事件。所以,只要刪除與您的委託及其相關協議相關的任何內容即可。

我可能會做的LocationManager類獨立的,並修改方法更新:

+(LocationManager *)sharedInstance 
{ 
    static LocationManager *_sharedInstance = nil; 
    static dispatch_once_t oncePredicate; 
    dispatch_once(&oncePredicate, ^{ 
     _sharedInstance = [[self alloc] init]; 
    }); 

    return _sharedInstance; 
} 

-(void)getUserLocation 
{ 
    if ([CLLocationManager locationServicesEnabled]) 
     [CLLocationManager startUpdatingLocation]; 
} 

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    [CLLocationManagerInstance stopUpdatingLocation]; 
    [[NSNotificationCenter defaultCenter] postNotificationWithName:@"LocationManagerDidUpdateLocation" object:newLocation]; 
} 

...那麼需要使用這個類的任何的viewController會碰到這樣的:

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [[NSNotificationCenter defaultCenter] addObserverForName:@"LocationManagerDidUpdateLocation" object:self queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { 
     CLLocation *location = note.object; 
     ... 
    }]; 
} 

-(IBAction)getMyLocation:(id)sender { 
    [[LocationManager sharedInstance] getUserLocation]; 
} 

希望幫助和合理。