書寫一個完整的單例模式類,並封裝爲宏



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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章