Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

grandM

macrumors 68000
Original poster
Oct 14, 2013
1,539
304
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.
 
Using all static methods makes sense if the object doesn't keep any state. Using singletons provides more flexibility.
 
Using all static methods makes sense if the object doesn't keep any state. Using singletons provides more flexibility.
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?
 
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.
 
  • Like
Reactions: grandM
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.