Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa singleton and shared instances

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.

like image 926
Ajay Kumar Avatar asked Nov 08 '22 12:11

Ajay Kumar


1 Answers

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.

like image 177
Amin Negm-Awad Avatar answered Nov 15 '22 06:11

Amin Negm-Awad