我想获取用户的多个控制器上的当前位置,他们是导航控制器,tabbarcontroller,presentmodel控制器的一部分,所以基本上我真的不能做像self.navigationcontroller或self.tabBarController 。iPhone需要更新位置在多个控制器
我做什么我创建了一个LocationHelper和LocationHelperDelegate
@protocol LocationHelperDelegate
@required
- (void)locationUpdate:(CLLocation *)location; // Our location updates are sent here
- (void)locationError:(NSError *)error; // Any errors are sent here
@end
@interface LocationHelper : NSObject <CLLocationManagerDelegate>{
CLLocationManager *locationManager;
CLLocation *currentLocation;
id delegate;
}
@property (nonatomic, retain) CLLocation *currentLocation;
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, assign) id delegate;
@end
然后在我的.m文件我下面
-(id) init {
self = [super init];
if(self != nil){
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation
*)newLocation fromLocation:(CLLocation *)oldLocation {
if([self.delegate conformsToProtocol:@protocol(LocationHelperDelegate)]) {
[self.delegate locationUpdate:newLocation];
}
}
然后现在这是我在我做我需要位置更新的所有控制器。 在init方法
LocationHelper* locationHelper = [[LocationHelper alloc]init];
locationHelper.delegate = self;
[locationHelper.locationManager startUpdatingLocation];
,然后我实现
- (void)locationUpdate:(CLLocation *)location {
latitude = location.coordinate.latitude;
longitude = location.coordinate.longitude;
[locationHelper.locationManager stopUpdatingLocation];
}
我100%肯定这是不是做正确的方式,但我不知道我应该怎么做这个。基本上我只需要做一次startUpdatingLocation,然后我的所有控制器都会得到locationUpdate的通知,并且每个控制器都收到通知stopUpdatingLocation。
我在考虑让LocationHelper类有一个singleton,但是当所有控制器都获得它的实例时,他们可以将它们设置为委托自己,这似乎不对,因为委托是实例变量之一LocationHelper,它只能保存一个值。
所以,你可以看到我很困惑,请帮助。
非常感谢,只是澄清了一些事情,调度通知代码将在LocationHelper中的我的 - (void)locationManager:(CLLocationManager *)管理器didUpdateToLocation方法中,但是我应该在哪里放置代码[[NSNotificationCenter defaultCenter] addObserver :自。它是否在想要订阅通知的每个控制器的init方法中进行,并且我假定每个控制器都必须实现 - (void)requestFinishedHandler:(NSNotification *)通知方法是否正确? – Yogesh 2011-04-13 21:21:08
对我来说,在控制器的viewDidAppear :(或viewDidLoad :)中调用addObserver更合理:因为您还想在viewDidDisappear中调用removeObserver:(或viewDidUnload :)。我不是100%确定如果你不注销观察员会发生什么,但我可以猜测这不完全是“最佳做法”。 – 2011-04-13 22:27:24
非常感谢Cadaeic。 – Yogesh 2011-04-14 00:42:15