有两种方法
第一种,在init里面抛出异常,定义私有的init
- (instancetype)init { [self doesNotRecognizeSelector:_cmd]; return nil; } - (instancetype)initPrivate { self = [super init]; if (self) { } return self; } + (instancetype)sharedInstance { static MySingleton *sharedInstance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] initPrivate]; }); return sharedInstance; }
第二种,在init里面直接返回单例
- (instancetype)init { return [[self class] sharedInstance]; } - (instancetype)initPrivate { self = [super init]; if (self) { } return self; } + (instancetype)sharedInstance { static MySingleton2 *sharedInstance; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] initPrivate]; }); return sharedInstance; }
时间: 2024-10-08 04:48:46