ios - 在我的 AppDelegate 中保留一个 CLLocationManager 是一种好习惯吗?

标签 ios objective-c cllocationmanager

我的应用监控用户位置,包括一些后台位置监控。

我的 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/

相关文章:

ios - 如何使用 PFQuery 查询与数组的精确匹配?

ios - Swift - 防止创建类的两个引用

javascript - 在 cordova ios build 上添加 iTunesArtwork 和 iTunesArtwork@2

iphone - 如何在运行时从 UITableView 添加或删除行?

ios - UIScrollView 以编程方式使 contectview 的 subview 的动态高度和宽度

ios - 如何使用 KVO 传递值?

iOS - 无法将 NSString 对象添加到 NSMutableSet

ios 6 - 允许用户在街上创建 map 注释的应用程序返回具有相同坐标的多个注释

objective-c - 地理围栏后台应用程序可能吗?

iphone - 从 CLLocationManager 授权警报中检测按钮按下