声明和实现:
- #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__; \
- }
- #undef DEF_SINGLETON_AUTOLOAD
- #define DEF_SINGLETON_AUTOLOAD( __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__; \
- } \
- + (void)load \
- { \
- [self sharedInstance]; \
- }
使用:
在XX.h 头文件中做如下声明:
- AS_SINGLETON(MainVC)
在XX.m 文件中做如下实现:
- DEF_SINGLETON(MainVC)
这里演示的是单个线程的代码,如果是多线程的话,可以使用 @synchronizer() 指令防止多个线程同时执行这段代码。