總結一下,昨天項目中遇到的問題。
昨天APP在內存比較小的手機上經常閃退,Terminated due to memory issue或者Terminated due to signal 9。這是因為內存的原因閃退。后面用Instruments查看,發(fā)現有很多內存泄漏的地方,而且最高的時候,內存甚至達到了500M左右。
內存泄漏
然后用Instruments定位到,內存泄漏基本上都是因為AFNetworking引起的。
--解決辦法:
在自己的網絡層對AFNetworking封裝一個單例就好了,不要每次請求一個網絡就[AFHTTPSessionManager manager]
一次,那樣會造成嚴重的內存泄漏。
#import "LCAFHTTPSessionManager.h"
@implementation LCAFHTTPSessionManager
static AFHTTPSessionManager *_manager = nil;
+ (AFHTTPSessionManager *)sharedHTTPSession{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_manager == nil) {
_manager = [AFHTTPSessionManager manager];
_manager.requestSerializer.timeoutInterval = 15;
_manager.responseSerializer = [AFJSONResponseSerializer serializer];
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"charset=utf-8", @"text/plain", nil]; // 設置content-Type為text/html
}
});
return _manager;
}
@end
內存暴增
當然內存暴增的原因有很多,一般都是循環(huán)引用造成的,一直在創(chuàng)建,但是又沒有釋放等。
我這里內存暴增,最后主要是因為GIF圖片引起的,而我使用的是SDWebImage中加載GIF動畫的sd_animatedGIFNamed
方法,使本來所占內存只有幾十M的會暴增到將近500M。
--解決辦法:
換個加載GIF的三方庫就好了。推薦兩個:FLAnimatedImage和YLGIFImage。這兩個都非常輕量級,使用的時候也很簡單,需要將ImageView和Image兩個的頭文件都導入。
- FLAnimatedImage
// NSURL *url1 = [[NSBundle mainBundle] URLForResource:@"未讀公告動畫" withExtension:@"gif"];
// NSData *data1 = [NSData dataWithContentsOfURL:url1];
// FLAnimatedImage *animatedImage1 = [FLAnimatedImage animatedImageWithGIFData:data1];
FLAnimatedImage *image = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif"]]];
FLAnimatedImageView *imageView = [[FLAnimatedImageView alloc] init];
imageView.animatedImage = image;
imageView.frame = CGRectMake(0.0, 0.0, 100.0, 100.0);
[self.view addSubview:imageView];
- YLGIFImage
YLImageView* imageView = [[YLImageView alloc] initWithFrame:CGRectMake(0, 160, 320, 240)];
[self.view addSubview:imageView];
imageView.image = [YLGIFImage imageNamed:@"joy.gif"];
最后我兩個都試了一下,使用FLAnimatedImage的時候,內存最高達到160多M;而使用YLGIFImage的時候,內存最高達到120多M。都比原來使用SDWebImage要低很多。