Objective-C内存管理:我什么时候[发布]? [英] Objective-C Memory Management: When do I [release]?

查看:78
本文介绍了Objective-C内存管理:我什么时候[发布]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对内存管理方面的内容还是很陌生的.(垃圾收集器负责处理Java中的所有内容),但是据我了解,如果您为对象分配内存然后您必须在完成对象处理后立即将这些内存释放回计算机.

myObject = [Object alloc];

[myObject release];

现在,我的 Objective-C .m文件中只有3个部分: @Interface @Implementation main .我在程序结束时在这些家伙旁边释放了我的对象:

[pool drain];
return 0;

但是如果该程序复杂得多,在程序结束时释放 myObject 可以吗?

我想一个更好的问题是何时释放对象的已分配内存?我怎么知道[myObject release];放在哪里?

解决方案

这可能有点过分简化了,但是总的来说,您将要在声明它的位置释放它.

如果在某个特定的方法调用中声明一个对象,那么根据定义,您将在该方法调用结束时完成该对象(或至少该对象的句柄)……然后释放它. /p>

如果将一个对象声明为实例变量,那么按照定义,当实例被销毁时,将完成该操作……在该类的dealloc方法中释放它.

请记住,释放"不等于破坏".在应用程序中传递对象时,可能有一个以上的对象句柄存储在不同的地方……在这种情况下,发布"的意思是我已经用完了这个对象,但是其他人可能仍然使用它."仅当句柄"(保留计数)的数量达到零时,才会发生重新分配.

Apple有一些出色的内存管理文档,我可以在 解决方案

This is probably a little over-simplified, but in general, you are going to want to release it where you declared it.

If you declare an object INSIDE a particular method call, then by definition, you will be done with that object (or at least that handle to that object) at the end of that method call... release it then.

If you declare an object as an instance variable, then by definition you will be done with it when that instance is destroyed... release it in the dealloc method of that class.

Keep in mind that "release" does not equal "destroy." When passing objects around in your application, it may make sense to have more than one handle to that object stored in different places... in that case "release" means "I'm done with this object, but someone else may still be using it." Deallocation only occurs when the number of "handles" (retain count) reaches zero.

Apple has some fantastic documentation on memory management, I would check it out at developer.apple.com.

这篇关于Objective-C内存管理:我什么时候[发布]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆