ios中单例模式运用

来源:互联网 发布:db2 oracle 数据同步 编辑:程序博客网 时间:2024/05/02 02:18

什么是单例 ?

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

iOS开发中如何使用单例?

传统的单例构造方法

+ (id)sharedInstance {

static id sharedInstance;

if(sharedInstance == nil){

sharedInstance = [[]self alloc] init]

}

return sharedInstance;

}

多线程下的隐患 在多线程的情况下,如果两个线程几乎同时调用sharedInstance()方法会发生什么呢?

有可能会创建出两个该类的实例。

为了防止这种情况 我们通常会加上锁

+ (id)sharedInstance {

static id sharedInstance;

@synchronized(self)

if(sharedInstance == nil)

{ sharedInstance = [[]self alloc] init]

} }

return sharedInstance;

}

dispatch_once iOS 4.0 引进了 GCD ,其中的 **dispatchonce**,它即使是在多线程环境中也能安全地工作,非常安全。dispatchonce是用来确保指定的任务将在应用的生命周期期间,仅执行一次。以下是一个典型的源代码以初始化的东西。它可以优雅通过使用dispatch_once来创建一个单例。

+ (id)sharedInstance {

static dispatch_once_t once;

static id sharedInstance;

dispatch_once(&once, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; }

原创粉丝点击