单例 - 通过宏快速实现单例

创建一个.h文件,代码如下:

#ifdef __has_feature(objc_arc) // ARC模式下

//.h文件
#define singleton_h(name) +(instancetype)sharad##name;
//.m文件
#define singleton_m(name) static id _instanceType = nil;\
+(instancetype)sharad##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 //MRC模式下

//.h 拼接参数使用##
#define singleton_h(name) +(instancetype)sharad##name;

//.m 宏里面换行
#define singleton_m(name) static id _instanceType = nil;\
+(instancetype)sharad##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;\
}\
-(oneway void)release\
{\
\
}\
-(instancetype)retain\
{\
    return _instanceType;\
}\
-(instancetype)autorelease\
{\
    return _instanceType;\
}\
- (NSUInteger)retainCount\
{\
    return 1;\
}

#endif
  • 当需要创建单例类时
    1.导入此文件
    2.在单例类的.h文件中
#import "singleton.h"
@interface DBTools : NSObject
singleton_h(单例的名称)
@end

3.在单例类的.m文件中

@implementation DBTools
singleton_m(单例的名称)
@end

这样就快速的实现了单例类,并且通过条件编译进行了MRC和ARC的判断,在不同内存管理模式下实现相应的方法

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

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 1 场景问题# 1.1 读取配置文件的内容## 考虑这样一个应用,读取配置文件的内容。 很多应用项目,都有与应用相...
    七寸知架构阅读 6,888评论 12 68
  • 一、深复制和浅复制的区别? 1、浅复制:只是复制了指向对象的指针,即两个指针指向同一块内存单元!而不复制指向对象的...
    iOS_Alex阅读 1,441评论 1 27
  • 单例模式(SingletonPattern)一般被认为是最简单、最易理解的设计模式,也因为它的简洁易懂,是项目中最...
    成热了阅读 4,298评论 4 34
  • 关于爱情 你说 真想哭一场 为那没盛开就枯萎的爱情 为那再也回不去的曾经 泪滴似珍珠滑落 我说 别哭 缘份...
    栗宁言阅读 164评论 0 1