在项目开发,难免会用到单例,也就是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的混编了!