0x00 背景
项目中使用了大量的单例类,在账号切换后,无法释放,需要维护大量状态和逻辑处理。
0x01 解决方案
- 容器包装
- 引用计数
0x02 方案讲解
1. 容器包装
参考解决循环引用的方案,全局一个单例类,里面若干个weak属性变量,在登录成功后,存到全局单例的weak属性里面,这样就可以全局访问了,但其生命周期由登录后的类维护,登出,即释放。
2. 引用计数
这种模式适合,一个大的模块,底层用的同一个唯一的服务类,但又不想外部知道:
static NSInteger count = 0;
static Networking *shareInstance = nil;
static dispatch_semaphore_t semaphore = nil;
+ (void)load {
semaphore = dispatch_semaphore_create(1);
}
+ (instancetype)defaultNetworking {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
count ++;
if (shareInstance == nil) {
shareInstance = [[Networking alloc] init];
};
NSLog(@"Networking alloc count:%@", @(count));
dispatch_semaphore_signal(semaphore);
return shareInstance;
}
+ (void)releaseNetworking {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
count --;
if (count <= 0) {
count = 0;
shareInstance = nil;
}
NSLog(@"Networking dealloc count:%@", @(count));
dispatch_semaphore_signal(semaphore);
}