How do I share CLLocation throughout my app?
I'm developing an app which has several view controllers which make use of the users current location. Since the users current location should be the same no matter which view I'm in, I think it makes sense to share this location betw开发者_JAVA技巧een view controllers. Should I define a CLLocation in my Application Delegate and then set each view controllers usersCurrentLocation
to match this? When the location is updated by one view controller, how do I ensure each of the other view controllers pick up the change? To me this sounds like a job for a global variable, but I know they're not a very 'Cocoa' way of doing things. What's the correct way to do this? Code samples would be helpful.
Singletons are a perfectly Cocoa way of doing things, and a "Location Manager" singleton (or whatever you choose to call it) instantiated upon app launch can not only provide the information to anything that needs the information, but can also periodically check for a location change and send notifications to any listeners.
Matt Gallagher does a great job of explaining singletons on his blog, and includes a super-handy macro for doing the heavy lifting.
Instead of assigning a location as property, consider a CCLocationManager as property. Same amount of work and keeps itself up to date... Whenever you need the current location, just send it the location
message.
It's a philosophical question. If it's only a little data, then yeah, a named property in your app delegate is a fine way to handle it. Especially if it's a property of the app (like where it's running physically). I don't mind.
More data than that, and I prefer to create a singleton data manager class, so it can be gotten to globally but has its own namespace.
If I were you, I would have all your location management code live in the app delegate itself, and think of individual viewcontrollers as "clients" of the delegate's location manager, picking up the current state from the delegate's .currentLocation (or whatever) property as needed.
If you can handle some iffy accuracy from time to time, you might also consider using the "updates on significant change" mode of CLLocationManager, rather than real live GPS tracking.
精彩评论