OC的单例

195 阅读1分钟

单例这样写应该比较好

UserInformationManage.h

@interface UserInformationManage : NSObject

+ (instancetype)sharedInstance;

@end

UserInformationManage.m

static UserInformationManage * __instance = nil;

@interface UserInformationManage () <NSCopying, NSMutableCopying>

@end

@implementation UserInformationManage

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (__instance == nil) {
            __instance = [[[self class] alloc] init];
        }
    });
    return __instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    if (__instance == nil) {
    return [super allocWithZone:zone];
    }
    return __instance;
}

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

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

@end