1. 程式人生 > >ios oc單例宏定義

ios oc單例宏定義

turn isp fin sin spa pat har b- with

#undef AS_SINGLETON

#define AS_SINGLETON( __class ) \

- (__class *)sharedInstance; \

+ (__class *)sharedInstance;

#undef DEF_SINGLETON

#define DEF_SINGLETON( __class ) \

- (__class *)sharedInstance \

{ \

return [__class sharedInstance]; \

} \

+ (__class *)sharedInstance \

{ \

static dispatch_once_t once; \

static __class * __singleton__; \

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

return __singleton__; \

} \

+ (instancetype)allocWithZone:(struct _NSZone *)zone \

{ \

static dispatch_once_t once; \

static __class * __singleton__; \

dispatch_once(&once, ^{ __singleton__ = [super allocWithZone:zone]; } ); \

return __singleton__; \

}

使用方法:在.h中聲明AS_SINGLETON(__class)

      .m中聲明DEF_SINGLETON(__class)

解釋:為了防止別人不小心利用alloc/init方式創建示例,也為了防止別人故意為之,我們要保證不管用什麽方式創建都只能是同一個實例對象,這就得重寫allocWithZone;之前我是沒有這個的,這是alloc init 和shareinstance創建的不是同一個

參考鏈接:http://www.cocoachina.com/ios/20160713/17017.html?ref=myread這個寫的很詳細

ios oc單例宏定義