2
votes

In Apple's documentation for their example of a Singleton, and I do understand there's more than one way to skin a cat -- but why do they bother ensuring the instance is registered as static?

Take from: http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html

I'm referring to:

static MyGizmoClass *sharedGizmoManager = nil;

2

2 Answers

9
votes

I believe it is so that the variable can't be accessed from outside the file for which it is defined. Otherwise it would be globally accessible.

This enforces that a client must use -(id)sharedObject to access the singleton.

2
votes

The answer above is correct. Declaring the singleton's variable as static means that it only exists in the local scope of the file containing it, which is exactly what you want. Part of this is because this singleton model relies on lazy loading to create the singleton on its first use, and part of this is because you don't want outside access to the pointer which could lose the singleton in memory, or allow another instance to be created, thus making the whole thing pointless in the first place.