11. Create and use the singleton mode (macro) and createinstance Mode
1 //. h文2 2 # define ZWSingletonH (name) + (instancetype) shared ## name; 3 4 //. m file 5 # define ZWSingletonM (name) \ 6 static id _ instance; \ 7 \ 8 + (instancetype) allocWithZone :( struct _ NSZone *) zone \ 9 {\ 10 static dispatch_once_t onceToken; \ 11 dispatch_once (& onceToken, ^ {\ 12 _ instance = [super allocWithZone: zone]; \ 13 }); \ 14 return _ instance; \ 15} \ 16 \ 17 + (instancetype) shared # name \ 18 {\ 19 static dispatch_once_t onceToken; \ 20 dispatch_once (& onceToken, ^ {\ 21 _ instance = [[self alloc] init]; \ 22}); \ 23 return _ instance; \ 24} \ 25 \ 26-(id) copyWithZone :( NSZone *) zone \ 27 {\ 28 return _ instance; \ 29}
Note: The above Code only needs to be in the. h folder.
If you want to use it, enter ZWSingletonH (Class Name) in the. h file where you want to set the singleton mode class)
In the. m file, enter ZWSingletonM (class name)
When needed: [class name + shared class name]