首页 > 代码库 > 单例头文件
单例头文件
1 // 帮助实现单例设计模式 2 3 // .h文件的实现 4 #define SingletonH(methodName) + (instancetype)shared##methodName; 5 6 // .m文件的实现 7 #if __has_feature(objc_arc) // 是ARC 8 #define SingletonM(methodName) 9 static id _instace = nil; 10 + (id)allocWithZone:(struct _NSZone *)zone 11 { 12 if (_instace == nil) { 13 static dispatch_once_t onceToken; 14 dispatch_once(&onceToken, ^{ 15 _instace = [super allocWithZone:zone]; 16 }); 17 } 18 return _instace; 19 } 20 21 - (id)init 22 { 23 static dispatch_once_t onceToken; 24 dispatch_once(&onceToken, ^{ 25 _instace = [super init]; 26 }); 27 return _instace; 28 } 29 30 + (instancetype)shared##methodName 31 { 32 return [[self alloc] init]; 33 } 34 + (id)copyWithZone:(struct _NSZone *)zone 35 { 36 return _instace; 37 } 38 39 + (id)mutableCopyWithZone:(struct _NSZone *)zone 40 { 41 return _instace; 42 }43 44 #else // 不是ARC45 46 #define SingletonM(methodName) 47 static id _instace = nil; 48 + (id)allocWithZone:(struct _NSZone *)zone 49 { 50 if (_instace == nil) { 51 static dispatch_once_t onceToken; 52 dispatch_once(&onceToken, ^{ 53 _instace = [super allocWithZone:zone]; 54 }); 55 } 56 return _instace; 57 } 58 59 - (id)init 60 { 61 static dispatch_once_t onceToken; 62 dispatch_once(&onceToken, ^{ 63 _instace = [super init]; 64 }); 65 return _instace; 66 } 67 68 + (instancetype)shared##methodName 69 { 70 return [[self alloc] init]; 71 } 72 73 - (oneway void)release 74 { 75 76 } 77 78 - (id)retain 79 { 80 return self; 81 } 82 83 - (NSUInteger)retainCount 84 { 85 return 1; 86 } 87 + (id)copyWithZone:(struct _NSZone *)zone 88 { 89 return _instace; 90 } 91 92 + (id)mutableCopyWithZone:(struct _NSZone *)zone 93 { 94 return _instace; 95 }96 97 #endif
单例头文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。