Why do Apple not have their classes as pure singleton, for example, even though the UIApplication class gives you access to the UIApplication singleton, like:
UIApplication *sharedApplication = [UIApplication sharedApplication];
Nothing prevents you from explicitly instantiating a UIApplication instance, like:
UIApplication *newApplication = [[UIApplication alloc] init];
The result, however, is a runtime exception. The exception clearly states that only one instance of the UIApplication class can be alive at any one time.
Then why not have pure singleton by returning same instance in the default initializer?
I am asking this question to have clarity, when creating singleton on my project, to follow which way is better.
First of all you are right: What Apple calls a singleton is neither a real singleton in the widely accepted definition nor in Apple's definition.
[…] whereas with a singleton class, there can be only one instance of the class per process
However, implementing a shared instance is quite easy in Swift:
class SomeManager {
static let sharedInstance = SomeManager()
}
In Objective-C both approaches (singletons and shared instances) are implementable, but a shared instance is easier to implement again.
On the other hand there is no disadvantage of using the shared instance pattern. You should follow it.
BTW: You do not get an exception in all cases of shared instances. Some classes let you allocate a second instance, what is akin of illegal.
It's a standard that Apple made and we developers follow to make apps.
In short, Apple has chosen not to have their classes as Singletons as a DESIGN CHOICE. And, again concerning the runtime exception you had for UIApplication, each application is given only one UIApplication instance.
You just cannot create your own UIApplication and do as you like. It breaks the rule.
But, however, we as developers are free to create and use singletons in our applications any time we like. And, Apple shares no concern with us on doing that, either.
What matters is what design choice you use to develop the application! Apple has their way, we have our ways! And, as long as its working, everybody is happy!
As for the right way, that just doesn't exist. You create the way as you go along.
Apple chose that pattern due to the experiences of its developer, and what sought to be the best choice at the given time. And, that is followed till today as it is fine. Say it breaks someday, then Apple would happily change their standards.
And, as for your last question on which standard or pattern to follow, you can follow whichever way you feel the most comfortable with. It's your design choice!
Kind Regards,
Suman Adhikari