Singleton mode, Mode
In the lifecycle of an iOS application, sometimes we only need an instance of a class. For example, when a program starts, the application state is maintained by an instance of the UIApplication class. This instance represents the entire application object and can only be one instance, the role is to achieve the access and status of some shared resources in the application.
The following is an example of a singleton class.
# Import "DDZPerson. h "@ interface DDZPerson () <NSCopying> @ end @ implementation DDZPersonstatic DDZPerson * _ person; // implements the singleton mode. First rewrite allocWithZone + (instancetype) allocWithZone :( struct _ NSZone *) zone {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// only once _ person = [super allocWithZone: zone];}); return _ person;} // For the convenience of direct calls + (instancetype) sharedPerson {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ person = [[self alloc] init] ;}); return _ person ;}// implement the copyable method-(id) copyWithZone :( NSZone *) zone {return _ person;} @ end
Because basically all the class Singleton modes are similar
So they can be defined in a macro file.
# Define DDZSingletonH + (instancetype) sharedInstance; # define DDZSingletonM \ static id * _ instance; \ + (instancetype) allocWithZone :( struct _ NSZone *) zone {\ static deleoncetoken; \ dispatch_once (& onceToken, ^ {\_ instance = [super allocWithZone: zone] ;\\}) ;\\ return _ instance ;\}\+ (instancetype) sharedInstance {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^{\_ instance = [[self alloc] init] ;\\}); \ return _ instance; \} \-(id) copyWithZone :( NSZone *) zone {\ return _ instance ;\}View Code
The reason why I typed \ later is that the macro definition only recognizes the last row.
The recognition will continue only after the \ is knocked