如何使用?创建一个单例对象
- 引入头文件
#import MGSingleton.h
- 在
HttpTool.h
头文件添加MGSingletonH(HttpTool)
- 在
HttpTool.m
中添加MGSingletonM(HttpTool)
- 使用时创建一个单例:
HttpTool *tool = [HttpTool sharedHttpTool];
注意点
-
##
是宏拼接参数,传入什么,它就是什么 - 每一行最后加
\
识别继续下一行,最后一行代码不用加\
- 要把注释删掉,中间不能有注释
- 判断是不是arc环境
__has_feature(objc_arc)
宏文件,同时兼容ARC和MRC
- MGSingleton.h文件
#define MGSingletonH(name) +(instancetype)shared##name;
- MGSingleton.m文件
#if __has_feature(objc_arc)
#define MGSingletonM(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 MGSingletonM(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
MRC下retain返回本身,release不做事情,retainCount返回1、autorelease返回自己