利用dispatch_once创建单例

来源:互联网 发布:微信怎么转换淘宝链接 编辑:程序博客网 时间:2024/05/29 18:30

自苹果引入了Grand Central Dispatch (GCD)(Mac OS 10.6和iOS4.0)后,创建单例又有了新的方法,那就是使用dispatch_once函数,当然,随着演进的进行,还会有更多的更好的方法出现。下面将介绍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.


    dispatch_once不仅意味着代码仅会被运行一次,而且还是线程安全的,这就意味着你不需要使用诸如@synchronized之类的来防止使用多个线程或者队列时不同步的问题。


       在开发中我们会用到NSNotificationCenter、NSFileManager等,获取他们的实例通过[NSNotificationCenter defaultCenter]和[NSFileManager defaultManager]来获取,其实这就是单例。

我们先看下函数void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);其中第一个参数predicate,该参数是检查后面第二个参数所代表的代码块是否被调用的谓词,第二个参数则是在整个应用程序中只会被调用一次的代码块。dispach_once函数中的代码块只会被执行一次,而且还是线程安全的。

       接下来我们来实现自己的单例,这里有一个SchoolManager类,为这个类实现单例

[cpp] view plaincopy
  1. +(SchoolManager *)sharedInstance  
  2. {  
  3.     static SchoolManager *sharedManager;  
  4.       
  5.     static dispatch_once_t onceToken;  
  6.     dispatch_once(&onceToken, ^{  
  7.         sharedManager = [[SchoolManager alloc] init];  
  8.     });  
  9.       
  10.     return sharedManager;  
  11. }  

使用就按照如下方式获取唯一实例即可:

[cpp] view plaincopy
  1. SchoolManager *schoolManager = [SchoolManager sharedInstance];  

原文出自:http://blog.csdn.net/ryantang03/article/details/8622415

http://blog.csdn.net/iitvip/article/details/8501317   





0 0
原创粉丝点击