利用宏实现单例(在宏中写实现方法)

声明和实现:

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #undef  AS_SINGLETON  
  2. #define AS_SINGLETON( __class ) \  
  3.         - (__class *)sharedInstance; \  
  4.         + (__class *)sharedInstance;  
  5.   
  6. #undef  DEF_SINGLETON  
  7. #define DEF_SINGLETON( __class ) \  
  8.         - (__class *)sharedInstance \  
  9.         { \  
  10.             return [__class sharedInstance]; \  
  11.         } \  
  12.         + (__class *)sharedInstance \  
  13.         { \  
  14.             static dispatch_once_t once; \  
  15.             static __class * __singleton__; \  
  16.             dispatch_once( &once, ^{ __singleton__ = [[[self class] alloc] init]; } ); \  
  17.             return __singleton__; \  
  18.         }  
  19.   
  20. #undef  DEF_SINGLETON_AUTOLOAD  
  21. #define DEF_SINGLETON_AUTOLOAD( __class ) \  
  22.         - (__class *)sharedInstance \  
  23.         { \  
  24.             return [__class sharedInstance]; \  
  25.         } \  
  26.         + (__class *)sharedInstance \  
  27.         { \  
  28.             static dispatch_once_t once; \  
  29.             static __class * __singleton__; \  
  30.             dispatch_once( &once, ^{ __singleton__ = [[[self class] alloc] init]; } ); \  
  31.             return __singleton__; \  
  32.         } \  
  33.         + (void)load \  
  34.         { \  
  35.             [self sharedInstance]; \  
  36.         }  

使用:

在XX.h 头文件中做如下声明:

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. AS_SINGLETON(MainVC)  

在XX.m 文件中做如下实现:

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. DEF_SINGLETON(MainVC)  

这里演示的是单个线程的代码,如果是多线程的话,可以使用 @synchronizer() 指令防止多个线程同时执行这段代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值