功能开发到一定程度,就进入优化阶段.
今天来尝试一下内存泄露的调优
先理清楚几个基本概念:
1. 什么是内存泄露
就是你new了一个东西,但是没有及时的释放掉. 因为内存的东西是只增不减的,如果你不及时释放掉,就会这些无用的数据一直占用内存。最后撑爆掉
2.怎么解决内存泄露
释放掉就好了。专业说起来有一大堆,本质就是release
备注:目前iOS已有ARC模式,而且目前大部分APP都会遵从这种模式,所以大部分场景是不需要考虑内存泄露这些问题的
(但是用不用和需要不需要知道是2个概念,本着学习的原则,我们还是要know something...)
3. iOS怎么查看内存泄露
3.1 自己查代码。每次alloc 的时候,铭记release
3.2 使用instrument查看,截图如下:
Xcode: Product->Profile->Leak
http://www.cocoachina.com/industry/20140114/7696.html
常见技巧:
HandicapPickerAccessoryView* accessoryView = [HandicapPickerAccessoryView
viewWithNoHandicapClickedHandler:^(id sender) {
//
}
andConfirmClickedHandler:^(id sender) {
[weakSelf handicapUpdated:self.handicap];
}];
这里self.handicap就可能引发内存泄露,解决方案是:
__weak typeof(self) weakSelf = self;
HandicapPickerAccessoryView* accessoryView = [HandicapPickerAccessoryView
viewWithNoHandicapClickedHandler:^(id sender) {
//
}
andConfirmClickedHandler:^(id sender) {
[weakSelf handicapUpdated: weakSelf.handicap];
}];
备注点:加个weak的self就可以,不过留心点,之前遇到过同事代码写太快了,写成如下这样. (忘记了weak. ---这就属于心里知道,但是写错了,查代码也不是那么容易一看出来...)
typeof(self) weakSelf = self;
|
4. 特殊情况:Core Foundation object
目前已经使用了ARC. 但是还是出现了内存泄露的点
instrument查看下来是路径绘制的地方出现了问题
"CG::Path::copy_as_sequence_on_write()+0x63"
"DYLD-STUB$$malloc"
查下来是之前做了一个数字icon . 类似购物车,右上角显示已经买个几个物品。
有一段代码是这样子的
这个是基于内容(比如1,2,...n)绘制badge的形状(CGMutablePathRef).
使用其的地方如下:
CGPathRef badgePath = [self newBadgePathForTextSize:numberSize];
这里绘制的badgePath之后,是需要release. 有人说,我们不是使用了ARC么?它干嘛去了?关键时刻不出来释放啦?还是它对这种情况不作处理的?
说对了.
The compiler does not automatically manage the lifetimes of Core Foundation objects; you must call CFRetain and CFRelease (or the corresponding type-specific variants) as dictated by the Core Foundation memory management rules (see Memory Management Programming Guide for Core Foundation).
就是我们类型是区分的core foundation(C语言的接口) 和object type(OC语言的接口)的类型是不一样的,arc 只负责Objective-C type 的数据. 至于这2个的区别我后面会贴图,大家一看自然懂
所以解决方案就是:
- 自己墙角蹲5min,然后默默把badgePath释放掉
- 使用__bridge_transfer 其实就是将core foundation类型的数据转为Objective-C类型的数据,本质就是指针转换.
备注:这种牛逼的技术叫Toll-Free Bridging
参考如下:
Or you can use __bridge_transfer or CFBridgingRelease to move the ownership of the Core Foundation object to the under the Objective-C ARC object ownership.
__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.
ARC is responsible for relinquishing ownership of the object.
当然对于我而言自然就是 CGPathRelease(badgePath);
以上可能对很多高手来说是常识了罢了....
补充:
Toll-Free Bridging
https://developer.apple.com/library/ios/documentation/General/Conceptual/CocoaEncyclopedia/Toll-FreeBridgin/Toll-FreeBridgin.html