- 一般来说,我们在一个类中写单例,要是想考虑的全面,那么要考虑到各个因素。
- 因为我们不知道别人创建单例的时候,通过什么创建的。所以我们就必须把通过各个方式创建的单例,都写出来:
+(instancetype)sharedSoundTool{
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
//
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
//
+ (id)copyWithZone:(nullable NSZone *)zone{
return self;
}
//
#pragma mark - 在非ARC环境下,还要重写下面方法
+ (oneway void)release {
}
//
+ (instancetype)autorelease {
return self;
}
//
+ (instancetype)retain {
return self;
}
//
+ (NSUInteger)retainCount {
return 1;
}
- 这应该是最全面的单例的创建了吧,包括了各个方面,各个方式。
然后我们抽取到一个.h文件中:
#define ZYSingleton_h(name) +(instancetype)shared##name;
#if __has_feature(objc_arc) // arc环境
#define ZYSingleton_m(name) +(instancetype)shared##name{ \
static id instance = nil; \
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [[self alloc] init];\
});\
return instance;\
}\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static id instance = nil;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [super allocWithZone:zone];\
});\
return instance;\
}\
\
- (id)copyWithZone:(nullable NSZone *)zone{\
return self;\
}
#else // 非arc环境
#define ZYSingleton_m(name) +(instancetype)shared##name{ \
static id instance = nil; \
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [[self alloc] init];\
});\
return instance;\
}\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static id instance = nil;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
instance = [super allocWithZone:zone];\
});\
return instance;\
}\
\
+ (id)copyWithZone:(nullable NSZone *)zone{\
return self;\
}\
+ (oneway void)release {\
}\
\
+ (instancetype)autorelease {\
return self;\
}\
\
+ (instancetype)retain {\
return self;\
}\
\
+ (NSUInteger)retainCount {\
return 1;\
}
#endif
- 接下来使用起来就非常爽了:
- 现在我们想创建一个单例对象:
在.h文件中
#import "ZYSingleton.h"
@interface ZYHttpTool : NSObject
ZYSingleton_h(HttpTool)
@end
.m文件中:
@implementation ZYHttpTool
ZYSingleton_m(HttpTool);
@end
就完成了一个单例的创建,就是这么easy