直接在.h文件中书写下列宏定义,然后在需要书写单例模式的.m文件下,导入Singleton.h文件,然后直接调用Singleton_h(xxx)即可
xxx写自己起的名字
#define Singleton_h(name) +(instancetype)shared##name;
# if __has_feature(objc_arc)
#define Singleton_m(name) static id _instance;\
\
+(instancetype)shared##name{\
\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
\
+(instancetype)allocWithZone:(struct _NSZone *)zone{\
\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
-(id)copyWithZone:(NSZone *)zone{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone{\
return _instance;\
}
# else
#define Singleton_m(name) static id _instance;\
\
+(instancetype)shared##name{\
\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
\
+(instancetype)allocWithZone:(struct _NSZone *)zone{\
\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
-(id)copyWithZone:(NSZone *)zone{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone{\
return _instance;\
}\
\
-(oneway void)release{\
\
}\
\
-(instancetype)retain{\
return _instance;\
}\
\
-(instancetype)autorelease{\
return _instance;\
}\
\
-(NSUInteger)retainCount{\
return 1 ;\
}
#endif