今天忽然想写个单例不知道咋写了,所以想起来之前看的
王巍 (onevcat). “Swifter - Swift 必备 Tips (第四版)。
这本书中的写法,所以想想还是记录一下吧。
今天忽然想写个单例不知道咋写了,所以想想还是记录一下吧。
- OC版本写法一(这种写法不算是太严谨)
@implementation MyPeter
+ (id)sharedManager {
static MyPeter * staticInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
staticInstance = [[self alloc] init];
});
return staticInstance;
}
@end
- OC版本写法二(推荐这种写法)
static MyPeter * staticInstance = nil;
@implementation MyPeter
+(MyPeter *)sharedManager{
return [[self alloc] init];
}
- (instancetype)init{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
staticInstance = [super init];
});
return staticInstance;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
staticInstance = [super init];
});
return staticInstance;
}
- (nonnull id)copyWithZone:(nullable NSZone *)zone{
return staticInstance;
}
-(nonnull id)mutableCopyWithZone:(nullable NSZone *)zone{
return staticInstance;
}
@end
- swift版本写法一(swift 1.2之前版本写法)
class var shared : MyPeter {
struct Static {
static let sharedInstance : MyPeter = MyPeter()
}
return Static.sharedInstance
}
- swift版本写法二(swift 1.2之前版本写法)
private let sharedInstance = MyPeter()
class MyPeter: NSObject {
class var shared : MyPeter {
return sharedInstance
}
}
- swift版本写法三(没有特殊要求推荐使用这种写法)
class MyPeter {
static let shared = MyPeter()
private init() {}
}