Objective-C Singletons
Template for a singleton
While singletons are often overused that doesn’t mean there isn’t a place for them. It also doesn’t mean there isn’t a way to implement them that addresses some of the concerns of critics.
Shared Instance
Rather then looking at singletons as the sole instance of a class I prefer the shared instance perspective. That being there exists a shared global instance that does not negate the possibility of other instances.
The current recommended approach to implementation is to lazily create the shared instance with a method structurally similar to +initialize
. Inside the method would be a static variable to hold the instance as well as a dispatch_once()
in which the instance is initialized. That being said in order to provide other instances any initialization work should be done in the instance initializer which should be publicly accessable.
This approach has the benefits of only producing a single shared instance, that is created lazily, and may be used outside the singleton pattern.
License
Any source in this article is released under the ISC License.