Why is AppDelegate being used?

Discussion in 'iOS Programming' started by grandM, Nov 13, 2016.

  1. grandM, Nov 13, 2016
    Last edited: Nov 13, 2016

    grandM macrumors 6502a


    Oct 14, 2013
    Hi guys

    I'm looking at a tutorial in which an instance of CLLocationManager is being used. This instance is created in AppDelegate. It also uses info.plist to show an alertView to ask the user for permission to use his location. I wonder if somebody could explain me why this isn't done in a plain ViewController?

    I looked in the documentation and found "
    Keeping a strong reference to the location manager object is required until all tasks involving that object are complete. Because most location manager tasks run asynchronously, storing your location manager in a local variable is insufficient."

    However if you just went let lm = CLLocationManger() in a ViewController at the top you would have a strong reference to it to or am I mistaken? As the documentation states I cannot instantiate it in a function.

    Once again my sincere gratitude.
  2. Mascots macrumors 68000


    Sep 5, 2009
    If your view controller is nested within a navigation stack and is popped, it will be deallocated.
    If your view controller that is holding the only reference to CLLM, that reference will be lost so it would be deallocated as well and there's no guarantee that the work being performed would be completed, or even started.
  3. grandM thread starter macrumors 6502a


    Oct 14, 2013
    Thanks for your answer. Could you give an example in which CLLocationManager would still be needed after the view controller is popped? Is CLLocationManager not typically used in maps, etc?
  4. KALLT, Nov 14, 2016
    Last edited: Nov 14, 2016

    KALLT macrumors 601

    Sep 23, 2008
    CLLocationManager does more than that, but if you only need to use a subset of its functions, then storing are reference to it as a property in a view controller might as well work out for you. I like to put such functionality into a separate model class, as they usually require some boilerplate anyway, i.e. checking user permission. I do the same with Core Data and then use singletons if I need the class to retain a reference during the entire lifecycle, to clean up the code in the app delegate.

    You should read through the documentation here: https://developer.apple.com/reference/corelocation/cllocationmanager. Perhaps you can say what you would like to do with it.
  5. grandM thread starter macrumors 6502a


    Oct 14, 2013
    Tx once more! I am going through a tutorial and now and then I stumble into something of which I wonder why it was handled that way.

Share This Page