关闭

iOS开发---一句话写单例方法

171人阅读 评论(0) 收藏 举报
分类:

转自http://www.jianshu.com/p/3fd9f5a4d715

你想一句话写单例吗?
想就跟我一起来看看吧!(把单例定义成宏)

用法如下:

Paste_Image.png

Paste_Image.png

Paste_Image.png

Paste_Image.png
具体代码如下:
#define singletonInterface(classname)              +(instancetype)shared##classname;

#if __has_feature(objc_arc)

#define singletonImplemention(class) \
static id instanse;\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
    static dispatch_once_t onesToken;\
    dispatch_once(&onesToken, ^{\
        instanse = [super allocWithZone:zone];\
    });\
    return instanse;\
}\
\
+ (instancetype)shared##class\
{\
    static dispatch_once_t onestoken;\
    dispatch_once(&onestoken, ^{\
        instanse = [[self alloc] init];\
    });\
    return instanse;\
}\
\
- (id)copyWithZone:(NSZone *)zone\
{\
    return instanse;\
};
#else

#define singletonImplemention(class)  \
static id instanse;\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
    static dispatch_once_t onesToken;\
    dispatch_once(&onesToken, ^{\
    instanse = [super allocWithZone:zone];\
        });\
    return instanse;\
}\
\
+ (instancetype)shared##class\
{\
    static dispatch_once_t onestoken;\
    dispatch_once(&onestoken, ^{\
    instanse = [[self alloc] init];\
    });\
    return instanse;\
}\
\
- (id)copyWithZone:(NSZone *)zone\
{\
    return instanse;\
}\
\
- (oneway void)release {} \
- (instancetype)retain {return instance;} \
- (instancetype)autorelease {return instance;} \
- (NSUInteger)retainCount {return ULONG_MAX;}

#endif

另附代码下载地址:
http://pan.baidu.com/s/1jGItvgi

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:118828次
    • 积分:2054
    • 等级:
    • 排名:第19542名
    • 原创:66篇
    • 转载:146篇
    • 译文:0篇
    • 评论:2条
    最新评论