美文网首页iOS学习笔记
单例 ARC下以及MRC 一句代码搞定

单例 ARC下以及MRC 一句代码搞定

作者: 指尖猿 | 来源:发表于2016-08-01 11:27 被阅读50次

    最近的项目中需要用到(singletion)于是查看了一些资料,以及apple官方文档我发现一些有趣的事情

    例如我们常用的alloc 内部其实就是调用的+(id)allocWithZone:(NSZone *)zone 的方法

    要实现单例只需要改写这个方法即可

    可是考虑仅仅是这样并不严禁.如果有些同事新手 用alloc init 或new 或copy或类方法来创建呢? 在考虑到如果线程安全呢?,在ARC下以及MRC下的单例呢?身为一个程序猿我觉得这些应该得考虑上.

    谈到上述这些,我不禁在想,干脆我自己写一个工具类,涵盖所有.我喜欢简单偷懒,所以我就自己把ARC下MRC下的单例抽取成了一个宏,让新手们一句话就可以调用.好吧废话不叨叨了,其实我是话唠.下面是具体实现代码.看官copy过去一句即可调用

    #if __has_feature(objc_arc)

    #define singleton_h(name) +(instancetype)shared##name;

    #define singleton_m(name) static id _instanceType;\

    +(instancetype)shared##name\

    {\

    static dispatch_once_t onceToken;\

    dispatch_once(&onceToken, ^{\

    _instanceType = [[self alloc]init];\

    });\

    return _instanceType;\

    }\

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

    {\

    static dispatch_once_t onceToken;\

    dispatch_once(&onceToken, ^{\

    _instanceType = [super allocWithZone:zone];\

    });\

    return _instanceType;\

    }\

    -(id)copyWithZone:(NSZone *)zone\

    {\

    return _instanceType;\

    }

    #else

    #define singleton_h(name) +(instancetype)shared##name;

    #define singleton_m(name) static id _instanceType;\

    +(instancetype)shared##name\

    {\

    static dispatch_once_t onceToken;\

    dispatch_once(&onceToken, ^{\

    _instanceType = [[self alloc]init];\

    });\

    return _instanceType;\

    }\

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

    {\

    static dispatch_once_t onceToken;\

    dispatch_once(&onceToken, ^{\

    _instanceType = [super allocWithZone:zone];\

    });\

    return _instanceType;\

    }\

    -(id)copyWithZone:(NSZone *)zone\

    {\

    return _instanceType;\

    }\

    -(instancetype)autorelease\

    {\

    return _instanceType;\

    }\

    -(instancetype)retain\

    {\

    return _instanceType;\

    }\

    -(oneway void)release\

    {\

    \

    }\

    -(NSUInteger)retainCount\

    {\

    return 1;\

    }

    #endif

    各位一句话就可以调用了下面是调用代码

    #import#import "singleton.h"

    @interface DBTool : NSObject

    singleton_h(DBTool)

    @end

    请不要问我宏为什么要加\ 连空格也要加

    自己copy过去实操一下

    请大家多多支持指尖猿O(∩_∩)O谢谢!

    相关文章

      网友评论

        本文标题:单例 ARC下以及MRC 一句代码搞定

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