iOS单例的正确写法

1,134 阅读1分钟
//
//  Singleton.m
//  多读单写Demo
//
//  Created by Jason on 2019/3/20.
//  Copyright © 2019 友邦创新资讯. All rights reserved.
//

#import "Singleton.h"

@interface Singleton ()<NSCopying>

@end

@implementation Singleton

+ (id)shareInstance {
    static Singleton *_singleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _singleton = [[self allocWithZone:NULL] init];
    });
    return _singleton;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self shareInstance];
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

@end