單例宏的書寫

單例模式是iOS開發中常見的設計模式,怎麼樣快速創建單例宏呢?方法如下:

//-------------------------------------------------------------

//@name 單例宏

//-------------------------------------------------------------

#undef H_SINGLETON

#define H_SINGLETON( __class ) \

+ (__class *)sharedInstance;


#undef M_SINGLETON

#define M_SINGLETON( __class ) \

+ (__class *)sharedInstance \

{ \

static dispatch_once_t once; \

static __class * __singleton__; \

dispatch_once( &once, ^{ __singleton__ = [[self alloc] init]; } ); \

return __singleton__; \

}

使用很簡單:

只需要在需用定義單例類的.h文件裏寫代碼

H_SINGLETON(類名);

.m文件裏寫代碼

M_SINGLETON(類名)

這樣就創建了一個單例類,是不是很簡單??


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