Singleton mode-implemented with GCD and implemented with mode-GCD
To use GCD to implement the singleton mode:
Step 1. Create the header file XZSingleton. h with the following code:
//. H file # define XZSingletonH (name) + (instancetype) shared # name ;//. m file # if _ has_feature (objc_arc) # define XZSingletonM (name) \ static id _ instace; \\+ (id) allocWithZone :( struct _ NSZone *) zone \ {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^{\_ instace = [super allocWithZone: zone] ;\}); \ return _ instace; \}\+ (instancetype) shared # name \ {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instace = [self alloc] init]; \}); \ return _ instace ;\}\\-(id) copyWithZone :( NSZone *) zone \{\ return _ instace ;\}# else # define XZSingletonM (name) \ static id _ instace ;\\+ (id) allocWithZone :( struct _ NSZone *) zone \{\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^ {\ _ instace = [super allocWithZone: zone] ;\}); \ return _ instace ;\}\+ (instancetype) shared # name \ {\ static dispatch_once_t onceToken; \ dispatch_once (& onceToken, ^{\_ instace = [[self alloc] init] ;\}); \ return _ instace; \}\- (id) copyWithZone :( NSZone *) zone \{\ return _ instace ;\}\\-(oneway void) release {}\-(id) retain {return self ;}\-(NSUInteger) retainCount {return 1 ;}\-(id) autorelease {return self ;}# endif
Step 2. The Singleton class to be implemented, such as XZDataTool ool and XZDataTool. h XZDataTool ool. m Code are as follows:
#import <Foundation/Foundation.h>@interface XZDataTool : NSObjectXZSingletonH(DataTool)@end
#import "XZDataTool.h"@implementation XZDataToolXZSingletonM(DataTool)@end