views:

121

answers:

1

Cocoa is full of singletons. Is there a logical/conventional difference between when the Cocoa APIs use

NSSingletonObject *so = [NSSingletonObject defaultSingleton];

versus

NSSingletonObject *so = [NSSingletonObject sharedSingleton];

?

Not a huge thing, but I don't really see why sometimes one is used versus the other.

+6  A: 

I think it tends to be that if it is a true singleton (such as NSApplication) that you are using, then the -[JKFoo sharedFoo] convention is followed. If on the other hand the class provides access to a default instance but you can still create other instances (for example NSNotificationQueue or NSFileManager) then the -[JKBar defaultBar] convention is used.

Side note: if you are implementing a few of your own Cocoa singletons, then there is a useful OpenSource header you might want to take a look at :)

jkp
Thanks for the tip!
MikeyWard
Regarding implementing your own singleton, there are many recepies on the web for implementing a *true* singleton in Cocoa, but for the most part Objective-C handles things by convention rather than stricture. Don't waste your time writing a bullet-proof singleton unless your code will be used by many outside devs. If you document a class as being a singleton, Objective-C style generally says that's engough...if you use it as a non-singleton, that's your problem.
Barry Wark
NSApplication isn't a singlton. Nor NSNotificationCenter or NSFileManager. I'm not sure i can think of a singleton in Cocoa.
mustISignUp
@mustlSignUp: OK, if you're being pedantic, you are right, but I think most people would refer to these classes as singletons as do Apple - http://gemma.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html#//apple_ref/doc/uid/TP40002974-CH6-SW66.
jkp