码迷,mamicode.com
首页 > 其他好文 > 详细

单例宏

时间:2015-02-07 11:33:49      阅读:138      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!