IOS中单例怎么销毁,会造成内存泄露吗?

官方文档中是这么解释的:  
" When an application terminates, objects may not be sent a dealloc message since 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."  
大致的意思就是:当应用程序退出时,对象不会接受到一个dealloc消息,系统会自己清理所有的资源,Apple认为这样比去调用一个内存管理方法更有效率.  
 
Cocoa With Love的Matt关于我提问的解答是这样的:  
"You don't need to free data from a singleton -- it lasts until the program quits, so the dealloc method will never be invoked.  
 
If you need to close a network connection, or something else that actually needs to be ended, you should do this in a "close" method and invoke the "close" method on the singleton in your applicationWillTerminate: method of your application delegate."  
意思差不多和官方一样,应用退出时,dealloc方法不会被调用,并且他建议我避免在dealloc中去作网络或其他类似的必须终止的操作,而应该将这些操作放在applicationWillTerminate:中,以确定这些操作被执行.  
 
所以关于这个问题的研究暂时就告一段落了,得出的结论是:  
1.不用担心静态全局变量的内存的问题,系统会在应用程序结束之后,回收这些内存.  
2.应用程序结束时会直接回收所有的程序运行中的资源,而不调用对象的dealloc方法.  
3.不要将类似网络或文件的关闭(应该是任何)操作放在类的dealloc方法中执行.  
 
参考资料:  
1.Apple推荐Sinaleton方法的文档Cocoa Fundamental Guide:Cocoa Objects中Creating a Singleton Instance一节这里还有中文的  
2.Cocoa With Love中关于top-level data的话题:Singletons, AppDelegates and top-level data.这里讨论还了你需要全局数据的条件,还提供了另外一个方法存放全局的数据:放置在AppDelegates中,并且讨论了这种方法的不妥之处,建议和我一样的新手可以拜读一下.  
3.Apple解释应用程序退出时不调用dealloc方法的文档:Memory Management Programming Guide for Cococa:Object Ownship and Disposal中Deallocating an Object一节的important:一段  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值