建立一个单例不少办法。我先列举一个苹果官方文档中的写法。安全
固然,在iOS4以后有了另一种写法:多线程
该写法具备如下几个特性:app
1. 线程安全。函数
2. 知足静态分析器的要求。oop
3. 兼容了ARCthis
而后我还有点好奇的是dispatch_once,这个函数,没见过啊。spa
因而就到官方的文档里找找看,是怎么说的。.net
下面是官方文档介绍:线程
dispatch_once指针
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 dispatch_once_t 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.
Availability
Declared In
dispatch/once.h
咱们看到,该方法的做用就是执行且在整个程序的声明周期中,仅执行一次某一个block对象。简直就是为单例而生的嘛。并且,有些咱们须要在程序开头初始化的动做,若是为了保证其,仅执行一次,也能够放到这个dispatch_once来执行。
而后咱们看到它须要一个断言来肯定这个代码块是否执行,这个断言的指针要保存起来,相对于第一种方法而言,还须要多保存一个指针。
方法简介中就说的很清楚了:对于在应用中建立一个初始化一个全局的数据对象(单例模式),这个函数颇有用。
若是同时在多线程中调用它,这个函数将等待同步等待,直至该block调用结束。
这个断言的指针必需要全局化的保存,或者放在静态区内。使用存放在自动分配区域或者动态区域的断言,dispatch_once执行的结果是不可预知的。
总结:1.这个方法能够在建立单例或者某些初始化动做时使用,以保证其惟一性。2.该方法是线程安全的,因此请放心大胆的在子线程中使用。(前提是你的dispatch_once_t *predicate对象必须是全局或者静态对象。这一点很重要,若是不能保证这一点,也就不能保证该方法只会被执行一次。)