我需要释放局部变量吗?

发布于 2024-12-09 02:17:28 字数 121 浏览 0 评论 0原文

在我的应用程序中,我有一个在本地声明的 NSError:

NSError *error;

我是在 dealloc 方法中释放它还是需要在我声明它的方法中释放它?

In my app I have a NSError that I declare locally:

NSError *error;

Do I release it in dealloc method or do I need to release it in the method I declare it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

强者自强 2024-12-16 02:17:28

请阅读Cocoa内存管理指南,内存管理是个东西你应该完全理解。 (而且这并不难。)如果您在方法中声明一个变量,则在dealloc中没有指向它的指针,因此您无法在那里释放它——您只能在之前释放它它超出了范围。另一个问题是你是否应该释放它。这取决于它是基于堆栈的、自动释放的还是保留的变量:

float foo[] = {1, 2, 3}; // stack-based, no releasing necessary
NSString *foo = [NSString stringWithFormat:…]; // autoreleased, you must not release it
NSString *foo = [[NSString alloc] initWith…]; // retained, you must release it

Please read the Cocoa Memory Management Guide, memory management is something you should understand perfectly. (And it’s not hard.) If you declare a variable in a method, you don’t have a pointer to it in dealloc, therefore you can’t release it there – you can only release it before it goes out of scope. Another question is if you should release it at all. That depends on whether it is a stack-based, autoreleased or retained variable:

float foo[] = {1, 2, 3}; // stack-based, no releasing necessary
NSString *foo = [NSString stringWithFormat:…]; // autoreleased, you must not release it
NSString *foo = [[NSString alloc] initWith…]; // retained, you must release it
溺渁∝ 2024-12-16 02:17:28

您需要在本地release它 - 假设您通过alloc/new/copy或其他创建它>保留它。 (如果您只是从其他地方获取它而不分配或保留,那么它不属于您,您根本不应该释放。)

否则,一旦它超出本地范围,您将无法访问指针和对象将会泄漏。

You need to release it locally -- assuming you create it by alloc/new/copy or else retain it. (If you just get it from somewhere else without allocating or retaining, then it doesn't belong to you and you shouldn't release at all.)

Otherwise, once it goes out of local scope you have no access to the pointer and the object will leak.

入画浅相思 2024-12-16 02:17:28

您需要将其发布到本地。因为在 dealloc 方法中,我们释放类变量或类数据成员以及在整个实现文件中使用的那些变量(如外部变量)。

You need to release it locally. Because in dealloc method we release class variables or class data members and those variables that are used through out the implementation file (like extern variables).

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