obj-c 在一系列方法中自动释放变量
我是 Obj-C 的新手,我有一个关于自动释放的问题。可以为多个方法返回自动释放的变量吗?例如:
- (void) methodC {
Object anObj = [self methodB];
//Do something with anObj
}
- (Object *) methodB {
return [self methodA];
}
- (Object *) methodA {
Object anObj = [[anObj alloc] init];
release [anObj autorelease];
}
即使变量返回到方法链并在顶部使用,它是否仍然有效?还是必须在途中将其保留在某个地方?
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,在这种情况下它是有效的。您只需要担心如果有人耗尽自动释放池,变量就会被释放。只要您编写了沿途返回的每个函数并且没有显式耗尽自动释放池,您就不必担心对象被从您下面释放。
在绝大多数情况下,
NSRunLoop
中的代码负责耗尽自动释放池。当您将控制权从应用程序代码返回到 API 代码时(例如从touchesBegan
处理程序返回等),您不知道自动释放池是否会被耗尽,因此您必须假设最坏的情况也是如此。在这种情况下,您必须保留
任何您想要保留引用的对象。例如:
Yes, it will be valid in this case. You only have to worry about the variable being deallocated if somebody drains the autorelease pool. As long as you've written every function that returns along the way and you don't explicitly drain the autorelease pool, you don't have to worry about objects being deallocated from under you.
In the vast majority of cases, the code in the
NSRunLoop
takes care of draining the autorelease pool. When you return control from your application code to the API code (such as by returning from atouchesBegan
handler etc.), you don't know if the autorelease pool will be drained, so you have to assume in the worst case that it will. In that case, you have toretain
any objects you want to keep references to.For example:
该变量应该保持有效。仅当某个对象实际上由某个其他对象“拥有”并且可能会与其一起间接/无意地释放时,您才需要保留该对象。例如,如果您从数组中提取一个对象,然后释放该数组,则您的对象引用可能会变得无效,除非您显式保留它。
有关更多详细信息,请参阅 对象所有权和解除,特别是有关共享对象的自动释放和有效性的部分。后者使用以下代码来说明如何“意外地”使对象引用无效。
以下代码展示了如何使用
retain
缓解此问题。The variable should remain valid. You only need to retain an object if it is actually "owned" by some other object and could be indirectly/unintentionally released along with it. For example, if you extracted an object from an array and then released the array, your object reference could become invalid unless you explicitly retain it.
For more details, see Object Ownership and Dismissal, particularly the sections on Autorelease and Validity of Shared Objects. The latter uses the following code to illustrate how you could "accidentally" make an object reference invalid.
The following code shows how to mitigate this problem using
retain
.