singleton

Discussion in 'iOS Programming' started by grandM, Jan 12, 2019.

  1. grandM macrumors 65816

    grandM

    Joined:
    Oct 14, 2013
    #1
    I realize singletons being used in things as UserDefaults and so on. What escapes me however is why they exist at all. A singleton creates one instance. On this instance all (non-static) methods are called. The instance is created through a static property.

    Why not simply render all methods and properties static? Hence not creating the singleton but work via static methods and properties.
     
  2. PhoneyDeveloper macrumors 68040

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    Using all static methods makes sense if the object doesn't keep any state. Using singletons provides more flexibility.
     
  3. grandM thread starter macrumors 65816

    grandM

    Joined:
    Oct 14, 2013
    #3
    Can you elaborate on that? I presume that you mean that certain properties have a value with keeping state? If so you could have static properties holding values? I do not immediately notice the extra flexibility?
     
  4. PhoneyDeveloper macrumors 68040

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    Those two sentences weren't related. The flexibility comes when you want to make changes to the code for the future. Writing a normal class but having a singleton instance is easier to modify than implementing everything with static methods. You can also have a shared singleton but still allow making instances of the class that might be configured differently. I think Alamofire does this.

    A lot of people hate singletons because of how they interfere with unit tests (they can't be mocked easily).

    There are many things in apps that are modeled best as singletons. There's only one file system. There's only one UserDefaults. There's probably only one server that your app talks to, and so on. So using Singletons isn't going away soon.
     

Share This Page