开发者

Where to implement CLLocationManager

I have an app with a tab bar and 3 tabs. The current location of the user is going to be needed to be known on any of the three tabs. Would the best place to implement CLLocationManager be in the app delegate in this case?

Is it ok (good practise?) to put the CLLocationManager delegate methods in the app delegate m file?

Where would you sugges开发者_运维百科t i place the CLLocationManager as I'm going to be calling -startUpdatingLocation from any of the three tabs?

Thanks


The app delegate is a reasonable place to put it. Another option would be to create a custom singleton factory class that has a class method that returns your location manager delegate and implement the delegate methods there. That would keep your app delegate class cleaner.

Here's a skeleton singleton class implemention based off of Peter Hosey's "Singletons in Cocoa: Doing them wrong". This may be overkill, but it's a start. Add your delegate methods at the end.

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...


I simply included my LocationManager in my AppDelegate directly, since it added little code.

However if you are going to include your LocationManager in the AppDelegate, then you should consider using NSNotifications to alert your viewcontrollers of the location updates your AppDelegate receives.

See this link Send and receive messages through NSNotificationCenter in Objective-C?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜