Cocoa Singleton and Shared Instances

Cocoa Singleton conventions

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 :)

[edit: an even better singleton solution using GCD was pointed out by Mike Ash on his blog]

With the Objective-C/Swift Singleton model, why do we create a shared instance and not just use class methods?

You create a shared instance if you need to be able to store state. If you can get away with just class methods, that is definitely preferable. The less state you have in your app, especially with singletons, the fewer bugs you will create.

How to create singleton for each thread in Cocoa?

A singleton and one object per thread requirement is an contradiction.

You probably want a thread local object. That is one object specific for each thread.

Thread local objects can be implemented by using [NSThread threadDictionary].
There you could store such an object as NSValue which can hold even a pointer.



Related Topics



Leave a reply



Submit