单例宏的抽取(用于ARC和非ARC)

在项目开发,难免会用到单例,也就是SingleTon,一旦创建单例,除非完全将程序退出,否则单例对象会一直存在!开发中,也许我们会使用多个单例,但一次次创建又很麻烦,但万一遇到MRC 与 ARC混编,再设置单例会更头疼!这里是一个单例宏的抽取,写入到 .h 文件,使用时,导入该文件即可!

singleTon.h

// 帮助实现单例设计模式

// .h文件的实现
#define SingletonH(methodName) + (instancetype)shared##methodName; 

// .m文件的实现
#if __has_feature(objc_arc) // 是ARC
#define SingletonM(methodName) \
static id _instace = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
} \
return _instace; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super init]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
} \
\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
return _instace; \
}

#else // 不是ARC

#define SingletonM(methodName) \
static id _instace = nil; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
if (_instace == nil) { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
} \
return _instace; \
} \
\
- (id)init \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super init]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##methodName \
{ \
return [[self alloc] init]; \
} \
\
- (oneway void)release \
{ \
\
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return 1; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
    return _instace; \
} \
 \
+ (id)mutableCopyWithZone:(struct _NSZone *)zone \
{ \
    return _instace; \
}

#endif

使用如下:

在某一 .h文件写下面格式

#import <Foundation/Foundation.h>
#import "Singleton.h"

@interface HttpTool : NSObject

// 单例类的声明
SingletonH(HttpTool)

@end

在相应的 .m实现

#import "HttpTool.h"

@implementation HttpTool

// 单例类的实现
SingletonM(HttpTool)

@end

是不是很简单,很方便,不需要写那些繁琐的代码了!

#if __has_feature(objc_arc)  // 是ARC

#endif

这段代码是判断ARC和非ARC的宏。若在项目中有ARC和MRC混编的话,那这段代码可就派上用场了,比如:

  // 定义一个Person类并实例化对象
  Person *person = [[Person alloc] init];

  // 非ARC下进行释放
  #if !__has_feature(objc_arc)  // 非ARC
   [person release];
  #endif

这样就实现了ARC和MRC的混编了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值