在哪里实现CLLocationManager

时间:2009-12-07 19:28:12

标签: core-location

我有一个带标签栏和3个标签的应用。在三个选项卡中的任何一个上都需要知道用户的当前位置。在这种情况下,实施CLLocationManager的最佳位置是否应该在app委托中?

将CLLocationManager委托方法放在app delegate m文件中是否可以(好的做法?)?

您建议我在哪里放置CLLocationManager,因为我将从三个标签中的任意一个调用-startUpdatingLocation

由于

2 个答案:

答案 0 :(得分:5)

应用代表是一个合理的地方。另一个选择是创建一个自定义单例工厂类,它具有一个返回您的位置管理器委托的类方法,并在那里实现委托方法。这将使您的app委托类更清洁。

这是一个基于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...

答案 1 :(得分:1)

我直接在我的AppDelegate中包含了我的LocationManager,因为它添加了很少的代码。

但是,如果要在AppDelegate中包含LocationManager,则应考虑使用NSNotifications向viewcontrollers提醒AppDelegate收到的位置更新。

查看此链接 Send and receive messages through NSNotificationCenter in Objective-C?

相关问题