我的应用监控用户位置,包括一些后台位置监控。
我的 App Delegate 中有一个位置管理器,主要用于初始启动位置和后台更新。然后我在我的 View Controller ( map )中有另一个管理器,用于更具体的事件和快速引用。
我想知道将其重构为一个实例、保存在 App Delegate 中并在整个应用程序中引用它是否是一个好习惯:
self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[self.appDelegate.locationManager startUpdatingLocation];
最佳答案
为了扩展其他评论者的建议,我还建议将其放入自己的类中,如下所示:
// Header
@interface MyLocationManager : NSObject
+ (MyLocationManager *)sharedInstance;
@property (readonly) CLLocationManager *locationManager;
@end
// Implementation
@implementation MyLocationManager
- (id)init
{
self = [super init];
if (self) {
_locationManager = /* set up your location manager */;
}
return self;
}
+ (MyLocationManager *)sharedInstance
{
static MyLocationManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyLocationManager alloc] init];
});
return sharedInstance;
}
@end
然后,您可以通过调用 [MyLocationManager sharedInstance]
在应用中的任何位置使用您的 MyLocationManager
。
关于ios - 在我的 AppDelegate 中保留一个 CLLocationManager 是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20750990/