IOS--dispatch_once 创建单例singletons
2013-12-23 12:36
721 查看
+(id)shareUserManager { static id userManager; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ userManager = [[self alloc] init]; }); return userManager; }
Executes a block object once and only once for the lifetime of an application.
void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);
Parameters
predicate
A pointer to a de style="font-family: Courier, Consolas, monospace; color: rgb(102, 102, 102);" >dispatch_once_tde> structure that is used to test whether the block has completed or not.
block
The block object to execute once.
Discussion
This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.
If called simultaneously from multiple threads, this function waits synchronously until the block has completed.
The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.
dispatch_once不仅意味着代码仅会被运行一次,而且还是线程安全的,这就意味着你不需要使用诸如@synchronized之类的来防止使用多个线程或者队列时不同步的问题。
1 线程安全
2 很好满足静态分析器要求
3 和自动引用计数(ARC)兼容
4 仅需要少量代码
相关文章推荐
- iOS 利用dispatch_once创建单例
- iOS学习笔记42—利用dispatch_once创建单例
- IOS开发之dispatch_once创建单例
- iOS 使用 dispatch_once 创建线程安全的单例
- IOS 用dispatch_once创建单利
- iOS 开发-利用dispatch_once创建单例
- iOS学习笔记1—利用dispatch_once创建单例
- iOS 转载一篇利用dispatch_once创建单例的文章
- iOS 创建单例的方法 dispatch_once
- IOS 运用dispatch_once 创建单例 MARK
- iOS学习笔记 —利用dispatch_once创建单例
- iOS学习笔记42—利用dispatch_once创建单例
- IOS 使用dispatch_once 创建单例
- iOS学习笔记42—利用dispatch_once创建单例
- iOS中使用GCD的dispatch_once创建单例
- IOS开发之dispatch_once创建单例
- kidd风的IOS日志之利用dispatch_once创建单例
- IOS:利用dispatch_once创建单例
- IOS开发之dispatch_once创建单例
- iOS开发 -- 利用dispatch_once创建单例