您的位置:首页 > 移动开发 > IOS开发

iOS 创建单例的方法 dispatch_once

2014-11-29 22:14 218 查看
单例的运用场景是:一种类,该类只能实例化一个对象。

iOS 创建单例的方法有:dispatch_once
举例如下
假如有个全局的状态类,该类的接口部分如下:

@interface GlobalState ()
@end


该类的实现:

@implementation GlobalState

+ (GlobalState *)state
{
static GlobalState *state = nil;

static dispatch_once_t once;
dispatch_once(&once, ^{
state = [[M2GlobalState alloc] init];
});

return state;
}

@end


任何时候访问共享实例,需要做的仅是:

GlobalState* state = [GlobalState state];

该种方法的特点:

1 线程安全

2 很好满足静态分析器要求

3 和自动引用计数(ARC)兼容

4 仅需要少量代码
该方法的作用就是执行且在整个程序的声明周期中,仅执行一次 dispatch_once 当中的 block 对象。

有些需要在程序开头初始化的动作,也可以放到 dispatch_once 当中来执行,保证其仅执行一次。

这个函数需要一个断言来确定这个代码块是否执行,这个断言的指针要保存起来。

对于在应用中创建一个初始化一个全局的数据对象(单例模式),这个函数很有用。如果同时在多线程中调用它,这个函数将等待同步等待,直至该block调用结束。

这个断言的指针必须要全局化的保存,或者放在静态区内。使用存放在自动分配区域或者动态区域的断言,dispatch_once执行的结果是不可预知的。

使用该方法要注意的地方

(1)获取单例的方法为类方法

(2)用静态指针指向单例

(3)参数 dispatch_once_t 也为静态的,否则结果不可知。

以下是官方文档

dispatch_once

Executes a block object once and only once for the lifetime of an application.
Declaration
SWIFT
func dispatch_once(_predicate:UnsafeMutablePointer<dispatch_once_t>,

_ block:dispatch_block_t!)
OBJECTIVE-C
void dispatch_once(dispatch_once_t*predicate,dispatch_block_tblock);
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 (including Objective-C instance variables) is undefined.
Import Statement
import Dispatch
Availability
Available in iOS 4.0 and later.

dispatch_once_t
A predicate for use with the dispatch_once function.
Declaration
SWIFT
typealias dispatch_once_t =
Int
OBJECTIVE-C
typedef longdispatch_once_t;
Discussion
Variables of this type must have global or static scope. The result of using this type with automatic or dynamic allocation is undefined. Seedispatch_once for details.
Import Statement
import Dispatch
Availability
Available in iOS 4.0 and later.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: