单例

1)在ios开发中,单例的应用非常广。是在内存中只有唯一的实例,并且提供一个全局的访问方法。

----------------系统的

UIApplication:应用程序启动后唯一的副本

NSFlieManager:处理文件低些操作

NSUserDefault:用户偏好读写

NSNotificationCenter:监听通知/派发任务

----------------常用的实例

音乐播放器

网络请求

MVVM处理逻辑的单例

2)实现:

alloc方法会调用allocWithZone方法。既然所有内存分配最终都是allocWithZone,如果能保证只实例化一个副本。就像懒加载,写get方法目的也是为了属性只被实例化一次。

/**

 1. 定义一个静态的实例成员=>保证对象在内存中只有一个副本,而且是保存在静态区的

 

 static id instance;

 

 2. 提供一个全局的访问方法,都以 shared + 类名 格式定义

 

 + (instancetype)sharedSoundTools;

 

 3. 重写 allocWithZone 方法,=> 保证对象只被实例化一次,只分配一次内存空间

 static dispatch_once_t onceToken;

 dispatch_once(&onceToken, ^{

    instance = [super allocWithZone:zone];

 });

 return instance;

 

 4. 实现 shared 方法 => 保证对象只被 init(初始化) 一次

 static dispatch_once_t onceToken;

 dispatch_once(&onceToken, ^{

    instance = [[self alloc] init];

 });

 return instance; 

 */

 

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

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return  instance;
}

 

+(instancetype)sharedTools {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];

    });
    return instance;
}

// 先调用类方法sharedTools,然后只执行一次dispatchOnce实例化局部变量instanceself alloc会调用到allocWithZone,也一次执行生成单例变量。然后之后在调用sharedTools直接就返回instance了,因为在静态区,所以永远都这一个实例。

(3)Swift单例:

 static let sharedTools = NetWorkTools();
原文地址:https://www.cnblogs.com/sgxx/p/6051603.html