OC基础 单例
#undef AS_SINGLETON #define AS_SINGLETON( __class ) \ + (__class *)sharedInstance; #undef DEF_SINGLETON #define DEF_SINGLETON( __class ) \ + (__class *)sharedInstance \ { \ static dispatch_once_t once; \ static __class * __singleton__; \ dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } ); \ return __singleton__; \ }
上面是用宏来定义单例。
下面介绍我们常用的两种单例的写法:
第一种
static SingleClass *single = nil; + (id)shareInstance { if(!single) { single = [[SingleClass alloc] init]; } return single; }
第二种
+ (id)shareInstance { static SingleClass *single = nil; static dispatch_once_t predicate; dispatch_once(&predicate, ^{ single = [[self alloc] init]; }); return single; }