IOS中单例的设计

 时间:2026-02-16 01:51:33

1、单例模式的作用

可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问;

从而方便地控制了实例个数,并节约系统资源

2、单例模式的使用场合

在整个应用程序中,共享一份资源(这份资源只需要创建初始化 1 次)

3、单例模式在 ARC\MRC 环境下的写法有所不同,需要编写 2 套不同的代码

4、3.1 可以用宏判断是否为 ARC 环境

#if __has_feature(objc_arc)

// ARC

#else

// MRC

#endif

IOS中单例的设计

5、3.2 ARC中,单例模式的实现

(1)在.m中保留一个全局的static的实例

static id _instance;

(2)重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)

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

{

    @synchronized(self) {

        if (!_instance) {

            _instance = [super allocWithZone:zone];

        }

    }

    return _instance;

}

(3)提供1个类方法让外界访问唯一的实例

+ (instancetype)sharedDemo

{

    @synchronized(self) {

        if (!_instance) {

            _instance = [[self alloc] init];

        }

    }

    return _instance;

}

IOS中单例的设计

6、3.3 非ARC中(MRC),单例模式的实现(比ARC多了几个步骤)

(1)实现内存管理方法

- (id)retain { return self; }

- (NSUInteger)retainCount { return 1; }

- (oneway void)release {}

- (id)autorelease { return self; }

IOS中单例的设计

7、具体实现

8、4.1新建一个项目,名为“单例设计模式”

IOS中单例的设计

9、4.2新建一个名为“SingletonDemo”的类,继承自“NSObject”

IOS中单例的设计

IOS中单例的设计

IOS中单例的设计

10、4.3在类的头文件中设计一个创建单例对象的类方法:

+ (instancetype)sharedSingletonDemo;

IOS中单例的设计

11、4.4在类的.m文件中实现相应的方法

#import "SingletonDemo.h"

@implementation SingletonDemo

// 定义一个全局的static的实例

static id _instance;

/**

 *  重写allocWithZone:方法,在这里创建唯一的实例

 */

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

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instance = [super allocWithZone:zone];

    });

    return _instance;

}

/**

 *  提供一个给外部调用的实例化类方法

 */

+ (instancetype)sharedSingletonDemo

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instance = [[self alloc] init];

    });

    return _instance;

}

/**

 *  为了考虑得更全面一些,把copy策略创建对象的方法也重写一遍

 */

+ (id)copyWithZone:(struct _NSZone *)zone

{

    return _instance;

}

@end

IOS中单例的设计

IOS中单例的设计

  • 最全的iOS细节设计
  • iOS 设计的神细节有哪些?
  • 扁平化设计的ios风格
  • iOS helloworld
  • 怎样学好iOS?
  • 热门搜索
    三年级教师节手抄报 文化手抄报 中国传统手抄报 保护视力手抄报 清明时节祭英烈手抄报 讲卫生手抄报内容 手抄报图案大全 文明手抄报的资料 治污减霾手抄报 美术手抄报