简体   繁体   English

iPhone内存管理的模棱两可方案

[英]Ambiguous scenario for iPhone memory management

I have some difficulties to understand this scenario. 我很难理解这种情况。

  • I create an object 我创建一个对象
  • I set its retained property to something 我将其保留的属性设置为某种
  • I forget to release its property 我忘了释放它的财产
  • I release the object 我释放对象

As I didn't release the property in the dealloc method, will the scenario result in a memory leak or will the property be released automatically? 由于我没有在dealloc方法中释放该属性,因此该方案是否会导致内存泄漏或该属性会自动释放?

The way Cocoa works is that memory management always looks locally balanced, within any one method*. Cocoa的工作方式是,在任何一种方法*中,内存管理始终看起来局部平衡。 This is kind of the point. 这是重点。 You should be able to tell whether you have a leak or error in a method just by looking at that one method. 您仅通过查看一个方法就能知道该方法是否泄漏或错误。 No global program knowledge required. 不需要全局程序知识。

It is your responsibility to release an object if you received the object from a -copy, -alloc, -retain, or -new method. 如果您从-copy,-alloc,-retain或-new方法收到对象,则有责任释放该对象。

If you do this: 如果您这样做:

[obj setProp:foo];

is it your responsibility to release foo? 释放foo是您的责任吗? No - see rules. 否-请参阅规则。 If obj retains it (and you're saying you happen to know that it does), then it is the responsibility of obj to release it, in its dealloc method if not sooner. 如果obj保留了它(您是说您碰巧知道它确实存在),那么obj的责任是释放它,如果不早的话,可以在其dealloc方法中释放它。

So if you did this, it's balanced, no matter what kind of property -prop is. 因此,如果您执行此操作,则-prop是哪种属性,它都是平衡的。

id obj = [[MyObject alloc] init];
[obj setProp:foo];
[obj release];

*except for within the implementations of init, copy, dealloc, and accessor methods. *除了init,copy,dealloc和accessor方法的实现内。

Yes, it's leak. 是的,这是泄漏。

Retain, alloc will increase the counter by one. 保留,分配将使计数器增加一。 Release will decrease the counter. 释放将减少计数器。 It will free the memory when the counter reaches zero. 当计数器达到零时,它将释放内存。

Think of setter as this: 认为二传手是这样的:

[newvalue retain];
[property release]; 
property = newvalue;

So.. 所以..

  • create an object => 0+1=1 创建一个对象=> 0 + 1 = 1
  • assign it to some object as a retain property => 1+1=2 将其分配给某个对象作为保留属性=> 1 + 1 = 2
  • release the object => 2-1=1 释放对象=> 2-1 = 1

You will have to release that object again sometime. 您将不得不再次释放该对象。 And, trust me autorelease doesn't work quite well in the iphone environment. 而且,请相信我, autorelease在iPhone环境中无法很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM