前言
好久没写东西了,因为最近懒了些,且找不到什么好的题材,所以准备对内存泄漏的问题做一篇整理。内存泄漏问题一直是项目开发中的一大问题,本文力求帮助从事过一段时间工作的ios开发者快速寻找app中的内存泄漏问题。部分内容比较基础,大神可无视勿喷。
一、从afnet说起
对于ios开发者,网络请求类afnetworking是再熟悉不过了,对于afnetworking的使用我们通常会对通用参数、网址环境切换、网络状态监测、请求错误信息等进行封装。在封装网络请求类时需注意的是需要将请求队列管理者afhttpsessionmanager声明为单例创建形式。对于该问题,afnetworking的作者在github上也指出建议使用者在相同配置下保证afhttpsessionmanager只有一个,进行全局管理,因此我们可以通过单例形式进行解决。下方展示部分核心代码:
(afhttpsessionmanager*)defaultnetmanager {
static afhttpsessionmanager *manager;
static dispatch_once_t oncetoken;
dispatch_once(&oncetoken, ^{
manager = [[afhttpsessionmanager alloc]init];
manager.responseserializer = [afhttpresponseserializer serializer];
});
return manager;
}
(void)get:(nsstring*)url parameters:(nsdictionary*)parameter returndata:(void (^)(nsdata * resultdata,nserror * error))returnblock{
//请求队列管理者 单例创建形式 防止内存泄漏
afhttpsessionmanager * manager = [httprequest defaultnetmanager];
[manager get:url parameters:parameter progress:^(nsprogress * _nonnull downloadprogress) {
} success:^(nsurlsessiondatatask * _nonnull task, id _nullable responseobject) {
returnblock(responseobject,nil);
} failure:^(nsurlsessiondatatask * _nullable task, nserror * _nonnull error) {
returnblock(nil,error);
}];
}
二、block循环引用
block循环引用的问题已是老经常谈了,至今已有多篇文章详细解释其原理及造成循环引用的原因等,不泛画图或实例列举,这里不一一赘述。总结一句话防止block循环引用就是要防止对象之间引用的闭环出现。举个开发中的实际例子,就拿很多人在用的mjrefresh说起
self.tableview.mj_header = [mjrefreshnormalheader headerwithrefreshingblock:^{
self.page = 1;
[self.dataarr removeallobjects];
[self loaddata];
}];
若在mjrefresh的执行block中调用当前self或其所属属性,一定要注意循环引用问题。我们简单分析下mjrefresh为什么会造成循环引用问题:
点击进入headerwithrefreshingblock对应方法即可
#pragma mark - 构造方法
(instancetype)headerwithrefreshingblock:(mjrefreshcomponentrefreshingblock)refreshingblock
{
mjrefreshheader *cmp = [[self alloc] init];
cmp.refreshingblock = refreshingblock;
return cmp;
}
这里仅有三行代码,无非就是创建了下拉刷新部分view然后返回,这里比较重要的是
cmp.refreshingblock = refreshingblock;这一句,这里的refreshingblock是属于mjrefreshheader的强引用属性,最后header会成为我们自己tableview的强引用属性mj_header,也就是说self.tableview强引用header, header强引用refreshingblock,如果refreshingblock里面强引用self,就成了循环引用,所以必须使用weakself,破掉这个循环。画图表示为:
循环引用示意图
闭环为:
self--->self.tableview--->self.tableview.mj_header--->self.tableview.mj_header.refreshingblock--->self
欧洲杯足彩官网的解决方案大家应该也不陌生
__weak typeof(self) weakself = self;
self.tableview.mj_header = [mjrefreshnormalheader headerwithrefreshingblock:^{
__strong typeof(self) strongself = weakself;
strongself.page = 1;
[strongself.dataarr removeallobjects];
[strongself loaddata];
}];
【⚠️strongself是为了防止内存提前释放,有兴趣的童鞋可深入了解,这里不做过多解释了。当然也可借助库进行解决,书写为
@weakify和
@strongify会更方便些。】
相应的对于自定义view中的一些block传值问题同样需要注意,与上述类似。
三、delegate循环引用问题
delegate循环引用问题比较基础,只需注意将代理属性修饰为weak即可
@property (nonatomic, weak) id delegate;
下图比较形象的说明了使用weak修饰就是为了防止viewcontroller和uitableview相互强引用内存无法释放的问题:
delegate循环引用
四、nstimer循环引用
对于定时器nstimer,使用不正确也会造成内存泄漏问题。这里简单举个例子,我们声明了一个类testnstimer,在其init方法中创建定时器执行操作。
#import "testnstimer.h"
@interface testnstimer ()
@property (nonatomic, strong) nstimer *timer;
@end
@implementation testnstimer
- (instancetype)init {
if (self = [super init]) {
_timer = [nstimer scheduledtimerwithtimeinterval:1 target:self selector:@selector(timerefresh:) userinfo:nil repeats:yes];
}
return self;
}
- (void)timerefresh:(nstimer*)timer {
nslog(@"timerefresh...");
}
- (void)cleantimer {
[_timer invalidate];
_timer = nil;
}
- (void)dealloc {
[super dealloc];
nslog(@"销毁");
[self cleantimer];
}
@end
在外部调用时,将其创建后5秒销毁。
testnstimer *timer = [[testnstimer alloc]init];
dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(5 * nsec_per_sec)), dispatch_get_main_queue(), ^{
[timer release];
});
最后的执行结果为
nstimer打印结果
可见testnstimer对象并没有正常释放,定时器仍然在无限的执行下去。
我们都知道定时器使用完毕时需要将其停止并滞空,但cleantimer方法到底何时调用呢?在当前类的dealloc方法中吗?并不是,若将cleantimer方法调用在dealloc方法中会产生如下问题,当前类销毁执行dealloc的前提是定时器需要停止并滞空,而定时器停止并滞空的时机在当前类调用dealloc方法时,这样就造成了互相等待的场景,从而内存一直无法释放。因此需要注意cleantimer的调用时机从而避免内存无法释放,如上的欧洲杯足彩官网的解决方案为将cleantimer方法外漏,在外部调用即可。
testnstimer *timer = [[testnstimer alloc]init];
dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(5 * nsec_per_sec)), dispatch_get_main_queue(), ^{
[timer cleantimer];
[timer release];
});
打印结果
五、非oc对象内存处理
对于ios开发,arc模式已发扬光大多年,可能很多人早已忘记当年retain、release的年代,但arc的出现并不是说我们完全可以忽视内存泄漏的问题。对于一些非oc对象,使用完毕后其内存仍需要我们手动释放。
举个例子,比如常用的滤镜操作调节图片亮度
ciimage *beginimage = [[ciimage alloc]initwithimage:[uiimage imagenamed:@"yourname.jpg"]];
cifilter *filter = [cifilter filterwithname:@"cicolorcontrols"];
[filter setvalue:beginimage forkey:kciinputimagekey];
[filter setvalue:[nsnumber numberwithfloat:.5] forkey:@"inputbrightness"];//亮度-1~1
ciimage *outputimage = [filter outputimage];
//gpu优化
eaglcontext * eaglcontext = [[eaglcontext alloc] initwithapi:keaglrenderingapiopengles3];
eaglcontext.multithreaded = yes;
cicontext *context = [cicontext contextwitheaglcontext:eaglcontext];
[eaglcontext setcurrentcontext:eaglcontext];
cgimageref ref = [context createcgimage:outputimage fromrect:outputimage.extent];
uiimage *endimg = [uiimage imagewithcgimage:ref];
_imageview.image = endimg;
cgimagerelease(ref);//非oc对象需要手动内存释放
在如上代码中的cgimageref类型变量非oc对象,其需要手动执行释放操作cgimagerelease(ref),否则会造成大量的内存泄漏导致程序崩溃。其他的对于corefoundation框架下的某些对象或变量需要手动释放、c语言代码中的malloc等需要对应free等都需要注意。
五、地图类处理
若项目中使用地图相关类,一定要检测内存情况,因为地图是比较耗费app内存的,因此在根据文档实现某地图相关功能的同时,我们需要注意内存的正确释放,大体需要注意的有需在使用完毕时将地图、代理等滞空为nil,注意地图中标注(大头针)的复用,并且在使用完毕时清空标注数组等。
- (void)clearmapview{
self.mapview = nil;
self.mapview.delegate =nil;
self.mapview.showsuserlocation = no;
[self.mapview removeannotations:self.annotations];
[self.mapview removeoverlays:self.overlays];
[self.mapview setcompassimage:nil];
}
六、大次数循环内存暴涨问题
记得有道比较经典的面试题,查看如下代码有何问题:
for (int i = 0; i < 100000; i ) {
nsstring *string = @"abc";
string = [string lowercasestring];
string = [string stringbyappendingstring:@"xyz"];
nslog(@"%@", string);
}
该循环内产生大量的临时对象,直至循环结束才释放,可能导致内存泄漏,解决方法为在循环中创建自己的autoreleasepool,及时释放占用内存大的临时变量,减少内存占用峰值。
for (int i = 0; i < 100000; i ) {
@autoreleasepool {
nsstring *string = @"abc";
string = [string lowercasestring];
string = [string stringbyappendingstring:@"xyz"];
nslog(@"%@", string);
}
}
若对autoreleasepool陌生,可查阅相关资料,毕竟不是一两句即可说明的。
附、如何检测app的内存泄漏问题
1、借助xcode自带的instruments工具(⚠️选取真机测试)
instruments
2、简单暴力的重写dealloc方法,加入断点或打印判断某类是否正常释放。
dealloc
3、通过facebook出品的工具类进行检测,感兴趣的童鞋可进行了解。
暂时写到这里,未完待续