在哪里实施CLLocationManager
问题描述:
我有一个标签栏和3个选项卡的应用程序。用户的当前位置将需要在三个选项卡中的任何一个上被知道。在这种情况下,实施CLLocationManager
的最佳位置是否在应用程序委托中?在哪里实施CLLocationManager
将CLLocationManager委托方法放入应用程序委托m文件是好的吗?
你会在哪里建议我放置CLLocationManager
,因为我打算从三个标签中的任何一个呼叫-startUpdatingLocation
?
谢谢
答
应用程序委托是一个合理的放置它的地方。另一种选择是创建一个自定义单例工厂类,该工厂类具有返回您的位置管理器委托并在其中实现委托方法的类方法。这将保持你的应用程序委托类更清洁。
这是一个基于Peter Hosey的"Singletons in Cocoa: Doing them wrong"的骨架单例类实现。这可能是矫枉过正,但这是一个开始。最后添加您的委托方法。
static MyCLLocationManagerDelegate *sharedInstance = nil;
+ (void)initialize {
if (sharedInstance == nil)
sharedInstance = [[self alloc] init];
}
+ (id)sharedMyCLLocationManagerDelegate {
//Already set by +initialize.
return sharedInstance;
}
+ (id)allocWithZone:(NSZone*)zone {
//Usually already set by +initialize.
@synchronized(self) {
if (sharedInstance) {
//The caller expects to receive a new object, so implicitly retain it
//to balance out the eventual release message.
return [sharedInstance retain];
} else {
//When not already set, +initialize is our caller.
//It's creating the shared instance, let this go through.
return [super allocWithZone:zone];
}
}
}
- (id)init {
//If sharedInstance is nil, +initialize is our caller, so initialze the instance.
//If it is not nil, simply return the instance without re-initializing it.
if (sharedInstance == nil) {
if ((self = [super init])) {
//Initialize the instance here.
}
}
return self;
}
- (id)copyWithZone:(NSZone*)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
- (void)release {
// do nothing
}
- (id)autorelease {
return self;
}
#pragma mark -
#pragma mark CLLLocationManagerDelegateMethods go here...
答
我只是将我的LocationManager直接包含在我的AppDelegate中,因为它添加了一些代码。
但是,如果你打算将你的LocationManager包含在AppDelegate中,那么你应该考虑使用NSNotifications来提醒你的视图控制器你的AppDelegate接收到的位置更新。
请参阅此链接 Send and receive messages through NSNotificationCenter in Objective-C?
我如何去实现一个单独的工厂类?这听起来像一个干净的方式,但我不能100%确定从哪里开始。 – joec 2009-12-07 19:51:05
查看上面的例子。 – 2009-12-07 20:00:45
代码格式没有工作(对不起!) – joec 2009-12-07 20:11:51