搜索
您的当前位置:首页正文

ios 开发中的单例模式

来源:知库网

其实iOS开发中的单例模式无非就是一个类创建的对象在程序中只有一个对象!

iOS中的单例模式有分为赖汉式和饿汉式单例两种但是我们在实际开发的过程中只要掌握一种赖汉式单例就行!赖汉式单例有两种实现方式一种是普通的方式(加锁)一种是GCD

首先我们先来看一下普通的方式(加锁实现)(大家需要注意这是在ARC下)

首先要想让一个类成为单例对象首先需要定义一个全局变量和三个方法:

// 用来保存唯一的单例对象

static id _instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone;

+ (instancetype)share+类名;

- (id)copyWithZone:(NSZone*)zone;

接下来我们就分别去实现这三个方法:

+ (instancetype)allocWithZone:(struct _NSZone *)zone

{

             if (_instance == nil) { // 防止频繁加锁

                      @synchronized (self) {

                            if (_instance == nil) { // 防止创建多次

                          _instance = [super allocWithZone:zone];

                                                           }

                                                       }

                                           }

                   return _instance;

}

+ (instancetype)share+类名

{

          if (_instance == nil) { // 防止频繁加锁

                   @synchronized (self) {

                            if (_instance == nil) { // 防止创建多次

                             _instance = [[self alloc] init];

                                                           }

                                                     }

                                            }

                          return _instance;

}

- (id)copyWithZone:(NSZone*)zone

{

return _instance;

}

最后就是我们的测试过程:

我分别用不同方式创建了四个对象,但是这个四个对象的内存地址打印如下图:

从内存地址的打印可见这四个对象是同一个对象!


接下来我就GCD实现单例模式做一下简单的介绍:

使用单例的步骤和上面的普通方式实现单例步骤一样只不过那三个方法的实现不一样而已啊!


Top