iOS严谨一些的单例写法
2018-03-01 本文已影响0人
_乱
常规不遵从NSCopying代理,不重写allocWithZone方法会导致用[class allow]init]写法和单例创建方法创建两个地址不相同的对象,无法做到实例的唯一性。写单例是需要重写allocWithZone方法保证用allocinit方法创建时实例的唯一性。
.h
#import <Foundation/Foundation.h>
@interface Singleton :NSObject<NSCopying>
+(instancetype)sharedInstance;
@end
.m
#import "Singleton.h"
static Singleton *_instance = nil;
@implementation Singleton
+(instancetype)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc]init];
});
return _instance;
}
+(id)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
- (id)copyWithZone:(NSZone *)zone
{
return _instance;
}
@end