美文网首页
ios 单例写法

ios 单例写法

作者: Ray0218 | 来源:发表于2020-08-22 10:42 被阅读0次

@implementation KLSignal

static KLSignal* _instance = nil;
+ (instancetype)shareInstance {
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:NULL] init] ;
        //不是使用alloc方法,而是调用[[super allocWithZone:NULL] init]
        //已经重载allocWithZone基本的对象分配方法,所以要借用父类(NSObject)的功能来帮助出处理底层内存分配的杂物
    }) ;
    return _instance ;
}

+(id)alloc{
    return [super alloc];
}

//用alloc返回也是唯一实例
+(id) allocWithZone:(struct _NSZone *)zone {
    
    return [KLSignal shareInstance] ;
}
//对对象使用copy也是返回唯一实例
-(id)copyWithZone:(NSZone *)zone {
    NSLog(@"copyWithZone");
    
    return [KLSignal shareInstance] ;//return _instance;
}
//对对象使用mutablecopy也是返回唯一实例
-(id)mutableCopyWithZone:(NSZone *)zone {
    return [KLSignal shareInstance] ;
}

@end


相关文章

  • iOS 单例模式

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

  • 单例的2种写法

    单例模式是iOS开发中最常用的设计模式,iOS的单例模式有两种官方写法,如下: 1,常用写法 import "Se...

  • ios~单例模式:

    在iOS OC中,一般我们都是用官方推荐的写法来写单例:GCD方式单例 分析单例 static SharedPer...

  • iOS-两种单例模式的实现

    单例模式是开发中最常用的写法之一,创建一个单例很多办法,iOS的单例模式有两种官方写法,如下: 不使用GCD 某些...

  • ios 单例写法

  • ios原生通知RN一套

    ios原生写法: 特别注意单例的方法+ (id)allocWithZone:(NSZone )zone *之前自定...

  • OC和Swift单例的写法

    一 、OC中单例的写法:1.普通单例的写法 2. 利用多线程来写单例 #pragma mark --- 普通单例写...

  • 单例

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

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • iOS单例的写法

    参考https://www.jianshu.com/p/6b012ebc10fe .h文件 ```objectiv...

网友评论

      本文标题:ios 单例写法

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