Retired Document
Important: This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
Singleton
A singleton class returns the same instance no matter how many times an application requests it. A typical class permits callers to create as many instances of the class as they want, whereas with a singleton class, there can be only one instance of the class per process. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.
You obtain the global instance from a singleton class through a factory method. The class lazily creates its sole instance the first time it is requested and thereafter ensures that no other instance can be created. A singleton class also prevents callers from copying, retaining, or releasing the instance. You may create your own singleton classes if you find the need for them. For example, if you have a class that provides sounds to other objects in an application, you might make it a singleton.
Several Cocoa framework classes are singletons. They include NSFileManager
, NSWorkspace
, and, in UIKit, UIApplication
and UIAccelerometer
. The name of the factory method returning the singleton instance has, by convention, the form shared
ClassType. Examples from the Cocoa frameworks are sharedFileManager
, sharedColorPanel
, and sharedWorkspace
.
Copyright © 2018 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2018-04-06