zoukankan      html  css  js  c++  java
  • 单例宏

    ARC&MRC都可使用的单例宏

    单例宏使用示例
    .h——>
    #import
    #import "singleDefine.h"
    @interface JYShared : NSObject
    SHARED_INTERFACE(JYShared)
    @end
    .m—>
    #import "JYShared.h"
    #import
    @implementation JYShared
    //使用单例宏,替代整个.m文件
    SHARED_IMPLEMENTATION(JYShared)
    @end
    singleDefine.h的内容

    //单例宏(懒汉式)的抽取,##可以拼接单个字符串,/可以拼接多个字符串

    //.h文件的抽取

    #define SHARED_INTERFACE(className) +(instancetype)shared##className;

    //.m文件的抽取

    #if !__has_feature(objc_arc)

    #define SHARED_IMPLEMENTATION(className)\

    static id instace;\

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

         static dispatch_once_t onceToken;\

        dispatch_once(&onceToken, ^{\

            instace=[super allocWithZone:zone];\

        });\

        return instace;\

    }\

    +(instancetype)shared##className{\

        static dispatch_once_t onceToken;\

        dispatch_once(&onceToken, ^{\

            instace=[[self alloc]init];\

        });\

        return instace;\

    }\

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

        return instace;\

    }\

    -(NSUInteger)retainCount{\

        return ULONG_MAX;\

    }\

    -(instancetype)retain{\

        return instace;\

    }\

    -(oneway void)release{\

    }\

    -(instancetype)autorelease{\

        return instace;\

    }

    //ARC

    #else

    #define SHARED_IMPLEMENTATION(className)\

    static id instace;\

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

    static dispatch_once_t onceToken;\

    dispatch_once(&onceToken, ^{\

    instace=[super allocWithZone:zone];\

    });\

    return instace;\

    }\

    +(instancetype)shared##className{\

    static dispatch_once_t onceToken;\

    dispatch_once(&onceToken, ^{\

    instace=[[self alloc]init];\

    });\

    return instace;\

    }\

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

    return instace;\

    }

    #endif

  • 相关阅读:
    思考:学习redis的数据结构应该从三个维度来学习?
    思考:一个程序员老说不会碰到或者用到复杂的数据结构或者算法,是这样吗?
    思考:软件系统设计的(前期)权衡?
    思考:一个推荐引擎工程师的能力覆盖
    思考:关于服务架构的取舍:
    模拟斗地主真人在线发牌
    java反射机制
    C-练习题
    java-线程的生命周期
    生产者和消费者模型
  • 原文地址:https://www.cnblogs.com/lijianyi/p/4278441.html
Copyright © 2011-2022 走看看