2013年1月27日星期日

dispatch_once

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

Available in iOS 4.0 and later.


dispatch_once_t

typedef long dispatch_once_t;

Variables of this type must have global or static scope.

利用GCD创建单例
  • GCD的 singleton,采用 dispatch_once 和 dispatch_once_t。dispatch_once_t 做predicate,而且它就是一个长整型
  • GCD创建单例,可以保证多线程状态下,单例创建的安全性,而不需要 double check 机制
  • dispatch_once 可以保证 block 在程序的整个生命周期内只执行一次
  • dispatch_once 是 function,dispatch_once_t 是 data type
eg. static dispatch_once_t once;
dispatch_once(&once, ^ { hudViewList = [[NSMutableArray alloc] init]; });

没有评论:

发表评论