iOS严谨一些的单例写法

常规不遵从NSCopying代理,不重写allocWithZone方法会导致用[class allow]init]写法和单例创建方法创建两个地址不相同的对象,无法做到实例的唯一性。写单例是需要重写allocWithZone方法保证用allocinit方法创建时实例的唯一性。

.h

#import

@interface Singleton :NSObject

+(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

你可能感兴趣的:(iOS严谨一些的单例写法)