如何释放在不同 AutoReleasePool 中分配的对象?
我对 Objective-C 中的内存管理有疑问。假设我有一个方法,它分配一个对象并将对该对象的引用存储为类的成员。如果我第二次运行相同的函数,我需要释放第一个对象,然后创建一个新的对象来替换它。假设函数的第一行是:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
这意味着将有一个不同的自动释放池。分配对象的代码如下:
if (m_object != nil)
[m_object release];
m_object = [[MyClass alloc] init];
[m_object retain];
问题是运行该方法的最后一行时程序崩溃:
[pool release];
我做错了什么?我该如何解决这个问题?
问候
艾伦
I have a problem with the memory management in Objective-C. Say I have a method that allocates an object and stores the reference to this object as a member of the class. If I run through the same function a second time, I need to release this first object before creating a new one to replace it. Supposing that the first line of the function is:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
This means that a different auto-release pool will be in place. The code to allocate the object is as follows:
if (m_object != nil)
[m_object release];
m_object = [[MyClass alloc] init];
[m_object retain];
The problem is that the program crashes when running the last line of the method:
[pool release];
What am I doing wrong ? How can I fix this ?
Regards
Alan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先对客观的c内存管理有一个大概的了解。你在这里混淆了很多不同的事情。例如,您不必保留 m_object,因为 alloc 已经将保留计数设置为 1。通常,当您释放对象时,您不会释放 AutoReleasePool。就像我说的,查找内存管理的文档(实际上非常好)。
First get a general understanding of the objective c memory management. You are confusing a lot of different things here. For example you don't have to retain the m_object since alloc already sets up the retain count with 1. Also normally you dont release you AutoReleasePool when you release a object. Like I said look up the documentation for memory management (pretty good actually).
自动释放池处理专门自动释放的对象
示例:
您的程序中必须至少有一个 NSAutoreleasePool ,以防某些代码尝试自动释放对象。如果这是您唯一的 NSAutoreleasePool,那么释放该池可能会导致您的问题。
Autorelease pools handle objects that have been specifically autoreleased
Example:
You have to have at least one NSAutoreleasePool in your program in case some code attempts to autorelease an object. If this is your only NSAutoreleasePool then releasing the pool maybe causing your problems.