单例 ARC下以及MRC 一句代码搞定

最近的项目中需要用到(singletion)于是查看了一些资料,以及apple官方文档我发现一些有趣的事情

例如我们常用的alloc 内部其实就是调用的+(id)allocWithZone:(NSZone *)zone 的方法

要实现单例只需要改写这个方法即可

可是考虑仅仅是这样并不严禁.如果有些同事新手 用alloc init 或new 或copy或类方法来创建呢? 在考虑到如果线程安全呢?,在ARC下以及MRC下的单例呢?身为一个程序猿我觉得这些应该得考虑上.

谈到上述这些,我不禁在想,干脆我自己写一个工具类,涵盖所有.我喜欢简单偷懒,所以我就自己把ARC下MRC下的单例抽取成了一个宏,让新手们一句话就可以调用.好吧废话不叨叨了,其实我是话唠.下面是具体实现代码.看官copy过去一句即可调用

#if __has_feature(objc_arc)

#define singleton_h(name) +(instancetype)shared##name;

#define singleton_m(name) static id _instanceType;\

+(instancetype)shared##name\

{\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instanceType = [[self alloc]init];\

});\

return _instanceType;\

}\

+(instancetype)allocWithZone:(struct _NSZone *)zone\

{\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instanceType = [super allocWithZone:zone];\

});\

return _instanceType;\

}\

-(id)copyWithZone:(NSZone *)zone\

{\

return _instanceType;\

}

#else

#define singleton_h(name) +(instancetype)shared##name;

#define singleton_m(name) static id _instanceType;\

+(instancetype)shared##name\

{\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instanceType = [[self alloc]init];\

});\

return _instanceType;\

}\

+(instancetype)allocWithZone:(struct _NSZone *)zone\

{\

static dispatch_once_t onceToken;\

dispatch_once(&onceToken, ^{\

_instanceType = [super allocWithZone:zone];\

});\

return _instanceType;\

}\

-(id)copyWithZone:(NSZone *)zone\

{\

return _instanceType;\

}\

-(instancetype)autorelease\

{\

return _instanceType;\

}\

-(instancetype)retain\

{\

return _instanceType;\

}\

-(oneway void)release\

{\

\

}\

-(NSUInteger)retainCount\

{\

return 1;\

}

#endif




各位一句话就可以调用了下面是调用代码

#import#import "singleton.h"

@interface DBTool : NSObject

singleton_h(DBTool)

@end

请不要问我宏为什么要加\ 连空格也要加

自己copy过去实操一下

请大家多多支持指尖猿O(∩_∩)O谢谢!

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

推荐阅读更多精彩内容

  • 单例设计模式: - 1.就是在整个项目中,这个类的对象只能被初始化一次。拥有唯一的一个实例 - 2.这个唯一的...
    Hevin_Chen阅读 358评论 0 0
  • 在开发中经常会用到单例设计模式,目的就是为了在程序的整个生命周期内,只会创建一个类的实例对象,而且只要程序不被杀死...
    不要重名就好阅读 560评论 0 0
  • 在开发中经常会用到单例设计模式,目的就是为了在程序的整个生命周期内,只会创建一个类的实例对象,而且只要程序不被杀死...
    VincentHK阅读 688评论 0 3
  • 线程间的通信 从子线程回到主线程 延时执行 iOS常见的延时执行有两种方式p 调用NSObject的方法 p 使用...
    一抹月光3053阅读 785评论 1 12
  • 文/沐叁 每日写作第33天。昨天小米屋复盘总结了一个多月来的变化,有进步也有困顿,但更多的是对未来满满的期许。 如...
    沐叁阅读 215评论 4 2