views:

3321

answers:

2

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;

+6  A: 

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.

Jason Medeiros
I use a singleton in a similar fashion across multiple files/modules.. it doesn't give me any issues accessing it.
Coocoo4Cocoa
Did you declare it in the .h or .m file? In the .m (where it's supposed to be) that shouldn't be the case.
Jason Medeiros
+1  A: 

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.