美文网首页
iOS创建单例

iOS创建单例

作者: iOS小洁 | 来源:发表于2023-03-07 21:36 被阅读0次

OC单例

避免调用alloc创建新的对象

避免copy创建新的对象

+ (id)sharedInstance
{
    // 静态局部变量
    static Singleton *instance = nil;
    
    // 通过dispatch_once方式 确保instance在多线程环境下只被创建一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 创建实例
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}

// 重写方法【必不可少】
+ (id)allocWithZone:(struct _NSZone *)zone{
    return [self sharedInstance];
}

// 重写方法【必不可少】
- (id)copyWithZone:(nullable NSZone *)zone{
    return self;
}

Swift 单例

public class FileManager { 
    public static let shared = FileManager() 
    private init() {    } 
}

public class FileManager {
    public static let shared = {
    // ....
    // ....
    return FileManager() 
  }() 
  private init() { }
}

相关文章

  • iOS 创建单例的方法

    iOS 创建单例的方法 方法一: 方法二:

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • ios -- 创建单例

    + (JYueMyTaskManagerService*)sharedMyTaskService { static...

  • ios创建单例

    最近公司项目其中的一个控制器需要做成单例,以保证收到推送或应用内消息时弹出的是同一个界面,看了下相关资料和视频,现...

  • iOS单例创建

    常规的创建单例 .h文件中 .m文件 使用GCD写 .h中 .m文件中

  • iOS单例创建

  • iOS创建单例

    在开发过程中经常会遇到需要单例的时候,然后很多时候大家写的单例其实并不符合要求。下面介绍一个标准的单例。 一般来说...

  • iOS - 单例创建

    Swift创建单例 代码如下:Swift5 对应OC创建单例

  • iOS单例

    在iOS开发中单例用的非常普遍,比如说通知中心,NSUserDefauld等都都是单例模式,原来以为创建一个单例是...

  • iOS 单例模式

    关于单例模式的详解,看完这几篇,就完全了然了。iOS 单例模式iOS中的单例模式iOS单例的写法

网友评论

      本文标题:iOS创建单例

      本文链接:https://www.haomeiwen.com/subject/pnhnldtx.html