使用dispatch_once实现单例
2017-12-13 16:36
381 查看
很多人实现单例会这样写:
@implementation XXClass + (id)sharedInstance { static XXClass *sharedInstance = nil; @synchronized(self) { if (!sharedInstance) { sharedInstance = [[self alloc] init]; } } return sharedInstance; }
相比之下:
@implementation XXClass + (id)sharedInstance { static XXClass *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; }
使用dispatch_once可以简化代码并且彻底保证线程安全,开发者无需担心加锁或同步。此外,dispatch_once更高效,它没有使用重量级的同步机制,若是那样做的话,每次运行代码前都要获取锁。相反,此函数采用“原子访问”来查询标记,以判断其所对应的代码原来是否已经执行过。在64位Mac OS X上测试,后者的执行速度要比前者快一倍。
相关文章推荐
- 使用dispatch_once实现单例模式
- iOS中使用dispatch_once实现单例及注意事项
- 使用dispatch_once实现单例模式
- 使用dispatch_once实现单例
- dispatch_once的实现分析
- 使用dispatch_once:创建单列
- 【iOS开发-91】GCD的同步异步串行并行、NSOperation和NSOperationQueue一级用dispatch_once实现单例
- 使用GCD的dispatch_once创建单例
- [Objective-C] 用 dispatch_once 实现单例
- (一二三)基于GCD的dispatch_once实现单例设计
- dispatch_once实现分析
- 单例模式 与用dispatch_once实现例子
- 单例的实现(dispatch_once_t synchronized)
- iOS中使用GCD的dispatch_once创建单例
- 使用GCD的dispatch_once创建单例
- dispatch_once的实现分析
- 如何使用dispatch_once优化代码性能
- 使用dispatch_once创建单例
- dispatch_once 实现单利
- dispatch_once 实现单例