ARC模式下的单例写法。

来源:互联网 发布:什么是美工设计助理 编辑:程序博客网 时间:2024/06/06 05:16

只有在EJShareModel *ddaa=[EJShareModel sharedInstances];才能保证唯一性。

+(EJShareModel *)sharedInstances

{

    __strong static EJShareModel *shared;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        shared =[[super alloc] init];

    });

    return shared;

}


在创建对象时:EJShareModel *ddaa=[EJShareModel sharedInstances],或者[EJShareModel alloc];或[[EJShareModel alloc] init];都返回同一个对象。如下图输出内容:

+(EJShareModel *)sharedInstances

{

    __strong static EJShareModel *shared;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        shared =[[super allocWithZone:nil] init];

    });

    return shared;

}

//allocWithZone是创建对象分配内存的源头,alloc也会调用该接口来分配内存创建对象。

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

{

    return [[self class] sharedInstances];

}

0 0