在哪里释放对象? dealloc或ViewDidUNload [英] Where to release an object? dealloc or ViewDidUNload

查看:107
本文介绍了在哪里释放对象? dealloc或ViewDidUNload的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们需要释放对象时,无论是在dealloc方法中还是在viewController的ViewDidUnload中释放对象?哪个会更好?

When we need to release an object,where to do it, either at the dealloc method or in the ViewDidUnload for a viewController? which would be better?

我认为viewDidUnload会做得更好,因为一旦视图控制器被卸载,对象就会被释放.在取消分配的情况下,请从

I think that viewDidUnload would do better, because once the view controller is unloaded the objects would be released. And in the dealloc case, from the documentation

当应用程序终止时, 对象可能无法发送给dealloc 信息.因为过程的记忆 在退出时自动清除,它 效率更高,只是允许 操作系统清理资源 而不是调用所有内存 管理方法.

When an application terminates, objects may not be sent a dealloc message. Because the process’s memory is automatically cleared on exit, it is more efficient simply to allow the operating system to clean up resources than to invoke all the memory management methods.

在应用程序退出时,可能不会向对象发送取消分配消息.

the objects may not be sent a dealloc message upon the Application quitting.

因此,我发现与释放对象相比,推迟释放对象会更好,从而减少应用程序占用的内存空间.

So I find it would be better if objects got released earlier, than postponing their release thereby reducing the memory footprint the Application takes.

如果我的理解是错误的,请纠正我.

If my understanding is wrong, please correct me.

感谢和问候, 克里希南

Thanks and Regards, Krishnan

推荐答案

是的,您的理解是错误的.

Yes, your understanding is wrong.

首先,当应用程序退出时会发生什么无关紧要,因为操作系统将释放您的应用程序分配的所有内存.在应用终止时不调用dealloc只是Apple加快此过程的方法.

First, it doesn't matter what happens when the application quits because the OS will free all the memory that your app allocated anyway. Not calling dealloc on app termination is just Apple's way to speed this up.

第二,调用viewDidUnload时不是卸载视图 controller ,而是仅卸载其 view .视图控制器一直处于活动状态,直到被释放为止.

Second, it is not the view controller that is unloaded when viewDidUnload is called but only its view. The view controller stays alive until it is deallocated.

viewDidUnload中,您必须释放视图中的那些对象以及可以在viewDidLoad中重新创建的所有对象(因为当视图控制器需要重新创建其视图时,将再次调用viewDidLoad ).这包括您所有的网点.您还必须将这些变量设置为nil,以避免过度释放它们.

In viewDidUnload, you have to release those objects that are part of the view and everything that can and will be recreated in viewDidLoad (because viewDidLoad will be called again when the view controller need to recreate its view). This includes all your outlets. You also have to set these variables to nil to avoid overreleasing them.

由于在dealloc中,您应释放视图控制器保留的所有对象,包括在viewDidUnload中包含的对象.

Because in dealloc, you should release all objects your view controller retains, including those you included in viewDidUnload.

看看Apple的任何示例代码,看看Apple如何做到这一点.

Have a look at any of Apple's sample code to see how Apple does this.

这篇关于在哪里释放对象? dealloc或ViewDidUNload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆