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

iOS开发中-单例的讲解

2016-09-09 10:09 232 查看

1.单例的作用

单例,即是在整个项目中,这个类的对象只能被初始化一次。它的这种特性,可以广泛应用于某些需要全局共享的资源中,比如管理类,引擎类,也可以通过单例来实现传值。UIApplication、NSUserDefaults等都是iOS中的系统单例。

首先来个线程不安全的写法

static SingleCase *manager = nil;

(SingleCase *)defaultManager {

if (!manager){

SingleCase = [[self alloc] init];

return manager;

}

}

再来来个苹果官方的写法

[cpp] view plaincopy

+ (AccountManager *)sharedManager
{
static AccountManager *sharedAccountManagerInstance = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
sharedAccountManagerInstance = [[self alloc] init];
});
return sharedAccountManagerInstance;
}


该写法具有以下几个特性:

1 线程安全。

2 满足静态分析器的要求。

3 兼容了ARC

下面是官方文档介绍对上面的代码介绍:

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.


Declared In

dispatch/once.h

单例的使用比如在我们多人开发中在整个应用程序各个地方都要用户的数据进行临时存储,在一定程度程度上提高了工作效率,避免重覆代码!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐