單例宏

使用方法:

  1. 聲明了兩個宏 SingleH(name) 和 SingleM(name) 兩個宏
  2. 創(chuàng)建一個想要實現(xiàn)單例模式的類.在.h文件中包含單例宏文件
    #import<single.h>
  3. 在.h文件中使用SingleH(name)宏
    #import <Foundation/Foundation.h>
    #import <Single.h>
    @interface CustomClass : NSObject
    SingleH();
    @end
  4. 在.m文件中使用SingleM(name)宏
    #import "CustomClass.h"
    @implementation CustomClass
    SingleM(customClass);
    @end

Single.h 文件

#define SingleH(name) +(instancetype)share##name;

#if __has_feature(objc_arc)
//條件滿足 ARC
#define SingleM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
\
return _instance;\
}\
\
+(instancetype)share##name\
{\
return [[self alloc]init];\
}\
\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}

#else
//MRC
#define SingleM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
\
return _instance;\
}\
\
+(instancetype)share##name\
{\
return [[self alloc]init];\
}\
\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
\
-(id)mutableCopyWithZone:(NSZone *)zone\
{\
return _instance;\
}\
-(oneway void)release\
{\
}\
\
-(instancetype)retain\
{\
    return _instance;\
}\
\
-(NSUInteger)retainCount\
{\
    return MAXFLOAT;\
}
#endif
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文首先實現(xiàn)單例模式,然后對單例代碼進行抽取宏,使其他類可以一句代碼實現(xiàn)單例(只介紹ARC環(huán)境)本文代碼[http...
    王技術(shù)閱讀 1,202評論 2 16
  • 單例模式 單例的目的:希望對象只創(chuàng)建一個單例,并且提供一個全局的訪問點 單例模式(arc) +(instancet...
    三歲就很乖閱讀 595評論 0 0
  • 單例模式 單例模式(arc) 類的實現(xiàn) 調(diào)用單例 單例模式(mrc) 除了上邊的方法我們在mrc的時候還需要增加一...
    董軍1990閱讀 3,520評論 11 35
  • 你說我倆很有默契,確實,一個從不掩飾,一個從不揭穿,何處笙歌繁華落,此生無分緣寂滅!
    李景雲(yún)閱讀 234評論 0 0
  • 請善待你的boss。boss就像一顆大樹的根,他強壯,有力。他為你提供了養(yǎng)料和舞臺,當你在風中翩翩起舞接受陽光的照...
    米衙閱讀 337評論 0 2

友情鏈接更多精彩內(nèi)容