單例模式是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(類名)
這樣就創建了一個單例類,是不是很簡單??