项目中,我们经常用到单例模式,并且不止一个类需要建立单例模式,为了方便快速创建单例模式类,编写如下宏。
使用方法很简单,步骤如下:
第一步,项目中新建一个.h文件,我们举例为:ThreadSingleton.h
,即包含宏的头文件
//说明:name为传入的参数,##name表示在后面拼接传入的name参数值。比如传入ABC,则最后变为shareBC
#define ThreadSingletonH(name) +(instancetype)share##name;
#if __has_feature(objc_arc)
//条件满足ARC
#define ThreadSingletonM(name) static id _tools;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_tools = [super allocWithZone:zone];\
});\
return _tools;\
}\
+ (instancetype)share##name{\
return [[self alloc] init];\
}\
- (id)copyWithZone:(nullable NSZone *)zone{\
return _tools;\
}\
- (id)mutableCopyWithZone:(nullable NSZone *)zone{\
return _tools;\
}
#else
//MRC
#define ThreadSingletonM(name) static id _tools;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_tools = [super allocWithZone:zone];\
});\
return _tools;\
}\
+ (instancetype)share##name{\
return [[self alloc] init];\
}\
- (id)copyWithZone:(nullable NSZone *)zone{\
return _tools;\
}\
- (id)mutableCopyWithZone:(nullable NSZone *)zone{\
return _tools;\
}\
-(oneway void)release{\
}\
-(instancetype)retain{\
return _tools;\
}\
-(NSInteger)retainCount{\
return MAXFLOAT;\
}
#endif
第二步,在需要使用到的类.h文件中,导入ThreadSingleton.h
#import <Foundation/Foundation.h>
#import "ThreadSingleton.h"
@interface ThreadGeneralSingletonTools :NSObject
//使用宏,括号内传入的参数,最终会变成提供出去的类方法 share+参数,比如这里是:shareThreadGeneralSingletonTools
ThreadSingletonH(ThreadGeneralSingletonTools)
@end
第三步,.m文件
#import "ThreadGeneralSingletonTools.h"
@implementation ThreadGeneralSingletonTools
//使用宏
ThreadSingletonM(ThreadGeneralSingletonTools)
@end
第四步,业务代码中使用单例模式类
ThreadGeneralSingletonTools *t = [ThreadGeneralSingletonTools shareThreadGeneralSingletonTools];
网友评论