AFHTTPSessionManager 内存泄漏的问题
首先,需要明确内存泄漏的概念。内存泄漏(Memory Leak)是指程序中已动态分配的堆内存由于某种原因程序未释放或无法释放,造成系统内存的浪费,导致程序运行速度减慢甚至系统崩溃等严重后果。
很多文章里描述:使用AFNetWorking过程中,AFHTTPSessionManager会导致内存泄漏的问题。所给出的解决方法是将AFHTTPSessionManager写成单例,用该单例进行网络请求。其实,这是使用者自己的问题。
原因是,AFHTTPSessionManager继承于AFURLSessionManager,AFURLSessionManager有个属性session,session类型是NSURLSession,NSURLSession将代理属性delegate强引用了,所以NSURLSession影响了其delegate的释放。



解决办法是,在调用NSURLSession进行请求后,等请求完毕后调用session的finishTasksAndInvalidate方法,或者调用取消session的invalidateAndCancel方法,再或者将session属性置成nil,这样AFURLSessionManager就能正常释放,这样就不需要将AFHTTPSessionManager写成单例来使用了。
调用其中的一个invalidate方法时,就会将其delegate引用计数减一,这样其delegate就能正常释放了,这里的delegate就是AFURLSessionManager。
静态分析、动态分析(Instruments—Leaks):
https://www.jianshu.com/p/9fc2132d09c7
内存检测三方工具:
http://wereadteam.github.io/2016/02/22/MLeaksFinder/
http://www.cocoachina.com/articles/16951