Each app has and has only one uiapplication, similar to UIApplication " [uiapplication sharedapplication]" This one class has and only unique instances of the design-singleton pattern.
single case design and key points
A singleton class is designed as shown in
There are a few points to note:
(1) The instance needs to be static to prevent it from being modified in other files;
(2) In view of the development habits, so the class method is named "Sharedxxx", and in which the unique instantiation;
(3) Alloc will call the Allocwithzone method, in order to maintain the singleton, it is necessary to rewrite the method;
(4) Check whether the two instance is nil has different meanings, the first check whether the instance is nil is often said double check lock, avoid repeated lock. Because after the first instantiation, each subsequent acquisition of the instance is not necessary to lock and other operations, directly return to the instance, the second check whether the instance is nil is obviously to ensure that the instance is unique.
(5) The significance of locking @synchronized is to ensure thread safety, to avoid the _instance to nil when multiple threads just get the instance at the same time, so at the same time a number of instances are generated. By locking to ensure that only one thread at a time to call, to ensure that the singleton;
(6) In order to prevent the creation of a new instance of copy, the same copywithzone has been re-guaranteed, a single case
GCD Way to achieve a single case
GCD mode single case design as shown
The role of Static
The static modifier global variable acts by restricting its scope so that the variable is valid only within the defined source file.
Conversely, if we remove the static modification, we can reference and modify the variables in other external files, and we will break the singleton.
Using a single instance in the MRC environment
If you are using a singleton in an MRC environment, there are some overrides in addition to the above design, so that the object reference count is always 1
iOS Development Note 2: Singleton mode (singleton)