如何在保证单例的安全(避免用户使用init方法)

      单例方法的方便性我就不说了,但是在使用的时候经常会害怕出现我定义了单例方法别人还是会用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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值