书写一个完整的单例模式类,并封装为宏

来源:互联网 发布:sem和seo 编辑:程序博客网 时间:2024/05/17 00:56



直接在.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

0 0
原创粉丝点击