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

  • 相关阅读:
    【SCOI 2011】 糖果
    【POJ 3159】 Candies
    【POJ 1716】 Integer Intervals
    【POJ 2983】 Is the information reliable?
    【POJ 1364】 King
    【POJ 1201】 Intervals
    【POJ 1804】 Brainman
    6月10日省中提高组题解
    【POJ 3352】 Road Construction
    【POJ 1144】 Network
  • 原文地址:https://www.cnblogs.com/lijianyi/p/4278441.html
Copyright © 2011-2022 走看看