單例模式-用GCD實現,模式-GCD實現
用GCD實現單例模式的步驟:
步驟1. 建立標頭檔 XZSingleton.h,裡面代碼如下:
// .h檔案#define XZSingletonH(name) + (instancetype)shared##name;// .m檔案#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
步驟2. 要實現的單例類,比如 XZDataTool,XZDataTool.h XZDataTool.m代碼分別 如下:
#import <Foundation/Foundation.h>@interface XZDataTool : NSObjectXZSingletonH(DataTool)@end
#import "XZDataTool.h"@implementation XZDataToolXZSingletonM(DataTool)@end