美文网首页
iOS allocWithZone写单例遇到的坑

iOS allocWithZone写单例遇到的坑

作者: huisedediao | 来源:发表于2016-12-27 11:34 被阅读0次

有好多人写单例喜欢用allocWithZone,这里说下自己遇到的坑。

先看下面的写法:

+(instancetype)shareManager
{
    return [XBDownloadTaskManager new];
}

-(instancetype)init
{
    if (self=[super init])
    {
          self.taskList=[NSMutableArray new];
    }
    return self;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static XBDownloadTaskManager *task=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        task=[super allocWithZone:zone];
    });
    return task;
}

似乎没有什么不对。
但是,打印该单例的taskList的时候,发现每次打印: [XBDownloadTaskManager shareManager].taskList ,taskList的内存地址都是不同的,就是这个坑了。

以为allocWithZone只分配一次内存,init 这个方法也只执行一次。而事实上,在 shareManager 方法中调用 [XBDownloadTaskManager new] ,每次都会调用init方法,每次都调用allocWithZone方法,确实是只分配了一次内存,但是if (self=[super init])这个条件是成立的,所以内次都跑了,所以,如果在init方法里有对属性的相关操作,也要加once操作

修改版:

-(instancetype)init
{
    if (self=[super init])
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            self.taskList=[NSMutableArray new];
        });
    }
    return self;
}

相关文章

  • iOS allocWithZone写单例遇到的坑

    有好多人写单例喜欢用allocWithZone,这里说下自己遇到的坑。 先看下面的写法: 似乎没有什么不对。但是,...

  • ios原生通知RN一套

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

  • iOS 单例的创建

    Objective-C创建单例 Swift创建单例 确保唯一性 复写allocWithZone、copyWithZ...

  • IOS 标准单例

    在ARC模式下 单例主要重写 两个方法 (instancetype)allocWithZone:(struct _...

  • 单例模式 Singleton Pattern

    单例模式-菜鸟教程 iOS中的设计模式——单例(Singleton) iOS-单例模式写一次就够了 如何正确地写出...

  • 单例

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

  • iOS 单例

    单例的创建 在 .h 文件中 在 .m 文件中这里初始化的时候使用 [[super allocWithZone:...

  • iOS 单例模式

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

  • iOS清除单例缓存

    iOS开发中最常见的设计模式就是单例模式,简单,好用;最近在单例上踩了一个坑,使用单例的过程中,不需要的时候需要清...

  • iOS开发 单例使用问题

    iOS开发 单例使用问题 iOS开发 单例使用问题

网友评论

      本文标题:iOS allocWithZone写单例遇到的坑

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