使用AFNetworking 3 内存泄露
在使用instruments做内存泄漏分析时,发现所有使用如下语句的地方都有内存泄漏,OMG: if (!_manager) { _manager = [AFHTTPSessionManager manager]; } 1 2 3 stack overflow上查了下并没有找到好的解决方案,去github的AFN的issue区查了下,确实有几个人提问了,但是每人给出解决方案。
我所用到的网络请求不是很复杂,不想再新建类去写单例了,就把单例放在了AppDelegate中,用到的时候在通过AppDelegate拿。因为需要用到AFHTTPSessionManager和AFURLSessionManager,所以就各写一个单例方法。 static AFHTTPSessionManager *manager ; static AFURLSessionManager *urlsession ; -(AFHTTPSessionManager *)sharedHTTPSession{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ manager = [AFHTTPSessionManager manager]; manager.requestSerializer.timeoutInterval = 10; }); return manager; } -(AFURLSessionManager *)sharedURLSession{ static dispatch_once_t onceToken2; dispatch_once(&onceToken2, ^{ urlsession = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; }); return urlsession; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 获得AFHTTPSessionManager和AFURLSessionManager单例 //AFHTTPSessionManager AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; AFHTTPSessionManager *manager = [app sharedHTTPSession]; //AFURLSessionManager AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; AFURLSessionManager *urlsession = [app sharedURLSession]; 1 2 3 4 5 6 7 全部替换完之后再用 instruments跑一遍,再也没有红叉了 ^_^ 。