如何释放在不同 AutoReleasePool 中分配的对象?

发布于 2024-08-26 06:12:49 字数 478 浏览 9 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

厌倦 2024-09-02 06:12:49

首先对客观的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).

扛刀软妹 2024-09-02 06:12:49

自动释放池处理专门自动释放的对象

示例:

[object autorelease];

您的程序中必须至少有一个 NSAutoreleasePool ,以防某些代码尝试自动释放对象。如果这是您唯一的 NSAutoreleasePool,那么释放该池可能会导致您的问题。

Autorelease pools handle objects that have been specifically autoreleased

Example:

[object autorelease];

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文