单例的正确使用姿势

Apple 官方文档

@interface Singleton : NSObject

@property (nonatomic, copy) NSString *name;

+ (Singleton *)sharedInstance;

@end

@implementation Singleton

static Singleton *sharedSingleton = nil;

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSingleton = [[super allocWithZone:NULL] init];
        
        // 实例变量的初始化一定要放在这里面(以确保调用init方法时不会多次初始化)
        sharedSingleton.name = @"cz";
    });
    return sharedSingleton;
}

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

- (instancetype)copy {
    return self;
}

- (instancetype)mutableCopy {
    return self;
}

@end

你可能感兴趣的:(单例的正确使用姿势)