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

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

用法如下:
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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容