Singleton mode is a kind of common software design pattern.
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.
If you want to have only one object in a class in the system, Singleton mode is the best solution to the aversion.
The most common singleton in iOS is uiapplication
Single-Instance implementation steps:
1. Overriding the Allocwithzone method
The Allocwithzone method is the method that will eventually be called when the object allocates memory space, overriding the method to ensure that only a memory space is allocated.
2. Set up the Shaerdxxx class method to facilitate other class invocation
+ (ID) Allocwithzone: (struct_nszone *) zone{StaticDemoobj *instance; //dispatch_once is thread-safe, Oncetoken defaults to 0 Staticdispatch_once_t Oncetoken; //Dispatch_once Macros Ensure that the instructions in the block code are executed only onceDispatch_once (&oncetoken, ^{ //in a multithreaded environment, it will only be executed once and instance will only be instantiated onceInstance =[Super Allocwithzone:zone]; }); returninstance;}+(instancetype) shareddemoobj{return[[Self alloc] init];}
There is also a common way to create a singleton:
Static Demoobj *instance; + (instancetype) shareddemoobj{ // If two threads are instantiated at the same time, it is possible to create two instances to the if (! Instance) { // thread 1 0x0000a // thread 2 0x0000b instance = [[Self alloc] init]; } // the pointer returned by the first thread has been modified! }
But the memory addresses of the objects instantiated [[Demoobj alloc] init] and [Demoobj shareddemoobj] are not the same, and the thread is unsafe.