天涯狂子的博客

潜心学习,让自己沉淀下来

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

转自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

阅读更多
个人分类: 设计模式
上一篇在使用代码布局的时候几个技巧,可减少 算坐标的麻烦!!
下一篇IOS用CGContextRef画各种图形(文字、圆、直线、弧线、矩形、扇形、椭圆、三角形、圆角矩形、贝塞尔曲线、图片)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭