查找内存泄漏时仪器中的颜色
我目前正在寻找 iPhone 应用程序中的内存泄漏问题。我正在使用 Instruments 来追踪导致泄漏的代码(越来越成为 Instruments 的朋友!)。现在,仪器显示两行:一行为深蓝色(第 146 行),另一行为浅蓝色(行 150)。通过一些试验和错误,我发现它们以某种方式连接起来,但在 Objective-C 和内存管理方面还不够好,还没有真正理解如何连接。
有谁知道为什么使用不同的颜色以及我的问题是什么?
我尝试释放 numberForArray 但在选择器视图中显示最后一行时应用程序崩溃。
所有想法表示赞赏!
(发布这个我也意识到第 139 行是多余的!Se 那里,已经是一个改进;-)
I'm currently hunting down a memory leak in my app for iPhone. I'm using Instruments to track down the code that is causing the leak (becoming more and more a friend of Instruments!). Now Instruments show two lines: one in dark blue (row 146) and one in a lighter blue (150). From some trial and error I get that they are connected somehow, but not good enough at Objective-C and Memory Management yet to really understand how.
Does anyone know why different colors are used and what could be my problem?
I have tried to release numberForArray but the the app crashes when showing the last line in a picker view.
All ideas appreciated!
(Posting this I also realize that line 139 is redundant! Se there, already an improvement ;-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,让我们看一下这段代码的对象分配/所有权行为...
numberForArray
被分配了-NSString stringWithFormat:
的结果,这是一个自动释放的目的。这意味着您不想想要释放它(正如您发现的那样)。然后将该对象添加到
glucoseLoader
NSMutableArray 中,NSMutableArray 将保留
它。您循环 100 次,创建 100 个对象并将它们添加到glucoseLoader
中。当glucoseLoader
被释放时,在第154行,它也会释放添加到其中的所有对象。但是等等,还有更多:
firstComponentRange
是使用-NSArray initWithArray:
从glucoseLoader
创建的。执行此操作时,源数组的所有元素都会添加到目标数组,目标数组将再次保留它们。那么,您何时/如何释放
firstComponentRange
?Ok, lets take a look at the object allocation/ownership behavior of this code...
numberForArray
is assigned the result of-NSString stringWithFormat:
, which is an auto-released object. That means that you do not want to release it (as you discovered).That object is then added to the
glucoseLoader
NSMutableArray, which willretain
it. You loop 100 times, creating 100 objects and adding them toglucoseLoader
. WhenglucoseLoader
is released, at line 154, it will also release all the objects added to it.But wait, there's more:
firstComponentRange
is created fromglucoseLoader
using-NSArray initWithArray:
. When you do that, all the elements of the source array are added to the destination, which will retain them again.So, when/how do you release
firstComponentRange
?Instruments 告诉您firstComponentRange 没有被释放(一个小泄漏)。由于数组保留了其内容,因此您也泄漏了 100 个 NSString 实例,这些实例分配在用深色带指示的行(更严重的泄漏)。
Instruments is telling you that firstComponentRange is not being released (a small leak). Since the array retains its contents, you ate thus also leaking 100 NSString instances, allocated at the line indicated with a darker band (a more significant leak).