ios 单例 三种写法
来源:互联网 发布:淘宝退款邮费 编辑:程序博客网 时间:2024/06/03 06:45
创建一个单例很多办法。我先列举一个苹果官方文档中的写法。
- static
AccountManager *DefaultManager = nil; -
- +
(AccountManager *)defaultManager { -
if (!DefaultManager) DefaultManager = [[self allocWithZone:NULL] init]; -
return DefaultManager; - }
@synchronized([globalObject class])
{
if(!obj)
obj = [[globalObject alloc] init];
}
return obj;
}
第二种方法使用了同步快,多线程同时访问是互斥的,但是这种方法效率不高,有锁的开销。
当然,在iOS4之后有了另外一种写法:
- +
(AccountManager *)sharedManager - {
-
static AccountManager *sharedAccountManagerInst ance = nil; -
static dispatch_once_t predicate; -
dispatch_once(&predicate, ^{ -
sharedAccountManagerInst ance = [[self alloc] init]; -
}); -
return sharedAccountManagerInst ance; - }
该写法来自
1. 线程安全。
2. 满足静态分析器的要求。
3. 兼容了ARC
然后我还有点好奇的是dispatch_once,这个函数,没见过啊。
于是就到官方的文档里找找看,是怎么说的。
下面是官方文档介绍:
dispatch_once
Executes a block object once and only once for the lifetime of an application.
Parameters
predicate
A pointer to a
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.
Declared In
dispatch/once.h
我们看到,该方法的作用就是执行且在整个程序的声明周期中,仅执行一次某一个block对象,正因为只执行一次,如果创建的单例对象被异常逻辑销毁了,那么单例也不会再创建了。简直就是为单例而生的嘛。而且,有些我们需要在程序开头初始化的动作,如果为了保证其,仅执行一次,也可以放到这个dispatch_once来执行。
然后我们看到它需要一个断言来确定这个代码块是否执行,这个断言的指针要保存起来,相对于第一种方法而言,还需要多保存一个指针。
方法简介中就说的很清楚了:对于在应用中创建一个初始化一个全局的数据对象(单例模式),这个函数很有用。
如果同时在多线程中调用它,这个函数将等待同步等待,直至该block调用结束。
这个断言的指针必须要全局化的保存,或者放在静态区内。使用存放在自动分配区域或者动态区域的断言,dispatch_once执行的结果是不可预知的。
- ios 单例 三种写法
- iOS 单例写法
- ios 单例写法
- ios单例写法
- iOS单例写法
- iOS 单例写法
- 单例模式的三种写法
- 单例模式的三种写法
- 单例模式常用三种写法
- ios 单例模式 两种写法
- ios 单例的几种写法
- IOS单例全局变量写法
- ios 单例的写法
- iOS 单例的写法
- ios 单例的写法
- C#单例模式的三种写法
- 转:c#单例模式三种写法
- C#单例模式的三种写法
- 第009讲 初识css 类选择器 id选择器 html选择器
- 如何敲代码
- CloseHandle()函数的使用
- DAO设计模式
- 进程之间的8种通信方式
- ios 单例 三种写法
- Android中的静态系统广播和动态系统广播
- Java基础 System,Runtime,Date,Calendar,Math-Random,Io流
- LIS4导出到WHONET程序说明
- 读入一个字符串,统计字符串中不同字符的出现频率。
- mysql 事务
- Ubuntu上搭建Hadoop环境(单机模式+伪分布模式)
- 13Roman to Integer
- j2se学习笔记-IO_2 转换流