0

我使用locationmanger來獲取我在iPhone上的當前位置。objective-c獲取位置並通知更新。觀察者?怎麼樣?

#pragma mark - Location handling 
-(void)doLocation { 
    self.locationManager = [[CLLocationManager alloc] init]; 
    [...] 
    SingletonClass *sharedSingleton = [SingletonClass sharedInstance]; 
    sharedSingleton.coordinate = [location coordinate]; 
} 

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
      fromLocation:(CLLocation *)oldLocation 
{ 
    [...] 
    SingletonClass *sharedSingleton = [SingletonClass sharedInstance]; 
    [sharedSingleton setCoordinate:CLLocationCoordinate2DMake(currentLat, currentLng)]; 

    NSLog(@"debug: self.currentLoc: %@", self.currentLoc); 

} 

這工作正常,我得到的位置座標有一些延遲,可以通過sharedSingleton訪問它們。當我有座標時,我必須觸發另一個需要座標作爲參數的函數。

在這裏,我的問題開始......

我怎麼現在,當座標檢索和我可以調用它需要的座標作爲輸入參數的其他功能。有沒有一種我可以使用的觀察者?如果,我該如何執行此操作?

我需要的東西,告訴我:嘿老兄,座標可供使用,這樣我就可以觸發下一個功能..

回答

1

可以使用NSNotificationCenter或委託。目標C中的委託模式非常常見。對於您將需要實現的協議在你的.h文件中,這樣的事情:

@protocol MyLocationManagerDelegate <NSObject> 
- (void) locationManager:(MyLocationManager *)manager didFindLocation:(CCLocation*) location 
@end 

//still in your .h file add a delegate that implements this protocol 
@property (nonatomic, assign) id<MyLocationManagerDelegate> delegate 

然後在當發現座標必須採取行動的其他類,表明它實現了MyLocationManagerDelegate協議,實施- (void) locationManager:(MyLocationManager *)manager didFindLocation:(CCLocation*) location方法。

分配您的位置管理器後,將其他班級設置爲代表。並在您的didUpdateToLocation方法只需撥打[self.delegate locationManager:self didFindLocation:self.currentLoc]

+0

瞭解委託模式http://enroyed.com/ios/delegation-pattern-in-objective-c-and-writing-custom-delegates/。似乎我需要走的路。必須現在用您的建議解決方案進行測試 – jerik