单例方法的方便性我就不说了,但是在使用的时候经常会害怕出现我定义了单例方法别人还是会用init方法初始化(尤其是在合作的迭代开发),这样会造成各种各样的错误,所以我向大家推荐2种避免这种问题的方法;
有两种方法
第一种,在init里面抛出异常,定义私有的init
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
- (instancetype)init {
//调用系统方法抛出异常
[self doesNotRecognizeSelector:_cmd];
return
nil;
}
- (instancetype)initPrivate {
//调用父类init方法避免死循环
self = [super init];
if
(self) {
}
return
self;
}
+ (instancetype)sharedInstance {
static
MySingleton *sharedInstance;
static
dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//调用initPrivate方法避免死循环
sharedInstance = [[self alloc] initPrivate];
});
return
sharedInstance;
}
|
第二种,在init里面直接返回单例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
- (instancetype)init {
//调用单例方法
return
[[self
class
] sharedInstance];
}
- (instancetype)initPrivate {
//调用父类init方法避免死循环
self = [super init];
if
(self) {
}
return
self;
}
+ (instancetype)sharedInstance {
static
MySingleton2 *sharedInstance;
static
dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//调用initPrivate方法避免死循环
sharedInstance = [[self alloc] initPrivate];
});
return
sharedInstance;
}
|