首页 > 其他 > 详细

单例宏

时间:2015-02-07 11:30:40      阅读:301      评论:0      收藏:0      [点我收藏+]

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

 

单例宏

原文:http://www.cnblogs.com/lijianyi/p/4278441.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!