我需要释放局部变量吗?
在我的应用程序中,我有一个在本地声明的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请阅读Cocoa内存管理指南,内存管理是个东西你应该完全理解。 (而且这并不难。)如果您在方法中声明一个变量,则在dealloc中没有指向它的指针,因此您无法在那里释放它——您只能在之前释放它它超出了范围。另一个问题是你是否应该释放它。这取决于它是基于堆栈的、自动释放的还是保留的变量:
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:您需要在本地
release
它 - 假设您通过alloc
/new
/copy
或其他创建它>保留
它。 (如果您只是从其他地方获取它而不分配或保留,那么它不属于您,您根本不应该释放。)否则,一旦它超出本地范围,您将无法访问指针和对象将会泄漏。
You need to
release
it locally -- assuming you create it byalloc
/new
/copy
or elseretain
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.
您需要将其发布到本地。因为在 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).