What is a single case
Singleton mode is a kind of common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources. Singleton mode is the best solution if you want to have only one object for a class in the system.
How to use single case in IOS development
Traditional single-instance construction method
+ (id)sharedInstance{ static id sharedInstance; if(sharedInstance == nil){ sharedInstance = [[]self alloc] init] } return sharedInstance;}
The hidden trouble under multi-thread
In the case of multithreading, what happens if two threads call the Sharedinstance () method almost simultaneously? It is possible to create two instances of the class. In order to prevent this situation, we usually add locks.
+ (id)sharedInstance{ static id sharedInstance; @synchronized(self) if(sharedInstance == nil){ sharedInstance = [[]self alloc] init] } } return sharedInstance;}
Dispatch_once
IOS 4.0 introduces GCD , **dispatchonce**, which is safe to work even in a multithreaded environment. Dispatchonce is used to ensure that the specified task is executed only once during the life cycle of the app. The following is a typical source code to initialize something. It can be elegant by using dispatch_once to create a single case.
+ (id)sharedInstance{ static dispatch_once_t once; static id sharedInstance; dispatch_once(&once, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance;}
iOS Development singleton mode dispatch_once