代码可以下载,链接在最下面,也可以直接复制下面的代码,自己新建一个类。
用法及其简单。例如
.h文件
#import <Foundation/Foundation.h>
//引入头文件
#import "singleton.h"
@interface DBTools : NSObject
//.h的宏
singleton_h(DBTools)
@end
.m文件
#import "DBTools.h"
@implementation DBTools
//.m的宏
singleton_m(DBTools)
@end
//============这是抽取的内容=================
#if __has_feature(objc_arc) //ARC
//.h 拼接参数使用##
#define singleton_h(name) +(instancetype)sharad##name;
//.m 宏里面换行
#define singleton_m(name) static id _instanceType;\
+(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;\
+(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
下载链接地址⬇️
http://pan.baidu.com/s/1mhKHg7Y