iOS中如何立即释放内存? [英] How free memory immediately in iOS?

查看:113
本文介绍了iOS中如何立即释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您进行释放时,您不会立即移除内存.我使用了这段代码,我可以看到使用前后的内存释放,它不会改变.好的,过段时间会发布.

When you do a release, you do not immediately remove the memory. I used this code and I can see the memory before and after the use of release and it do not change. Ok, it will be release after some time.

但是,在启动将使用大量内存的库之前,我可以做些什么来释放所有内存?或者我怎样才能立即释放内存?

But, what can I do for release all memory I can before start a library that will use a lot of memory? Or how can I immediately release memory?

推荐答案

内存管理是 iOS 中的一件大事,但这些信息在我的开发过程中帮助了我很多.

Memory Management is a big thing in iOS but this tidbit of information helped me a lot during my development.

每个对象都有一个保留计数",它通过调用retain"增加,通过调用release"减少.一旦保留计数达到 0,对象就会被释放,内存可以用于其他用途.

"Each object has a "retain count" which is increased by calling "retain" and decreased by calling "release". Once the retain count hits 0, the object is released and the memory can be used for something else.

您可以自动释放"对象.这意味着保留计数不会立即减少,而是会在下次排空当前自动释放池时减少.

You can "autorelease" objects. This means the retain count isn't immediately decreased, but is decreased the next time the current autorelease pool is drained.

iOS 应用有一个事件循环,您的代码在其中运行.在事件循环的每次迭代之后,自动释放池被排空.任何保留计数为 0 的对象都会被释放.

iOS apps have an event loop in which your code runs. After each iteration of the event loop, the autorelease pool is drained. Any object with a retain count of 0 is released.

默认情况下,自动释放的对象由不以 new、copy、mutableCopy、retain 或 init 开头的方法返回.这意味着您可以立即使用它们,但如果您不保留它们,则该对象将在运行循环的下一次迭代中消失.

By default, autoreleased objects are returned by methods that don't begin with new, copy, mutableCopy, retain or init. This means you can use them immediately but if you don't retain them the object will be gone on the next iteration of the run loop.

如果您未能释放保留的对象但不再引用它们,那么您将发生内存泄漏,这可以通过 Instruments 中的泄漏工具检测到.

If you fail to release retained objects but no longer reference them then you will have a memory leak, this can be detected by the leaks tool in Instruments.

一种策略是自动释放上述命名方法返回的所有内容,并将对象存储在保留属性中(或复制字符串).在对象的 dealloc 方法中,将所有属性设置为 nil.将保留/复制属性设置为 nil 会释放它当前指向的对象.只要您没有任何循环引用(通过不对父"对象(例如委托)使用保留属性来避免),您就永远不会遇到任何泄漏."

One strategy is to autorelease everything returned by the above named methods and store objects in retain properties (or copy for strings). In your object's dealloc method, set all your properties to nil. Setting a retain/copy property to nil releases the object that it currently points to. As long as you don't have any circular references (avoided by not using retain properties for "parent" objects such as delegates), you will never encounter any leaks."

这是此信息的线程链接

http://www.quora.com/What-is-the-best-way-to-understand-memory-management-in-iOS-development

这是一个很好的线程,包含一些有用的代码示例以及其他参考.

It's a good thread with some useful code examples as well as other references.

这篇关于iOS中如何立即释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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