1 StaticDemoobj *instance;2 3 /**4 1. Rewrite Allocwithzone and instantiate a static variable with dispatch_once5 2. Write a +sharedxxx to facilitate other class calls6 */7 8 //in iOS, the allocation of memory space for all objects will eventually call the Allocwithzone method9 //If you want to do a singleton, you need to override this methodTen //GCD provides a method that is designed to create a singleton One+ (ID) Allocwithzone: (struct_nszone *) Zone A { - StaticDemoobj *instance; - the //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 once -Dispatch_once (&oncetoken, ^{ + //in a multithreaded environment, it will only be executed once and instance will only be instantiated once -Instance =[Super Allocwithzone:zone]; + }); A at returninstance; - } - -+(instancetype) shareddemoobj - { - //If two threads are instantiated at the same time, it is possible to create two instances to in //if (!instance) { - // //Thread 1 0x0000a to // //Thread 2 0x0000b + //instance = [[Self alloc] init]; - // } the // //the pointer returned by the first thread has been modified! * //return instance; $ return[[Self alloc] init];Panax Notoginseng } - the + macro for a single case A the //. h + #defineSingleton_interface (Class) + (Instancetype) shared# #class; - $ //. M $ #defineSingleton_implementation (Class) - class*_instance; - the+ (ID) Allocwithzone: (struct_nszone *) Zone - { Wuyi Staticdispatch_once_t Oncetoken; theDispatch_once (&oncetoken, ^{ -_instance =[Super Allocwithzone:zone]; Wu }); - About return_instance; $ } - -+ (Instancetype) shared##class - { A if(_instance = =Nil) { +_instance = [[classalloc] init]; the } - $ return_instance; the}
ios-Single case