为什么要使用自动释放池? [英] Why use Autorelease pool?

查看:142
本文介绍了为什么要使用自动释放池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在main方法中创建了一个自动释放池,并且所有接收到自动释放消息的对象都存储在该池中,并在池耗尽时被释放.

I know there is an autorelease pool created in the main method and all the objects that receive autorelease message get stored in this pool and get released when the pool drains out.

但是一直有人说避免自动释放对象,以避免内存泄漏,进而导致应用程序崩溃.

But it is always said to avoid autoreleasing objects to avoid memory leaks and in turn app crashes.

那我们为什么以及在什么情况下应该使用autoreleasepool?

Then why and in which conditions should we use autoreleasepool?

Apple文档建议我们在使用线程时需要使用它们,因此在线程开始时我们需要创建一个自动释放池,在线程结束时将其耗尽,但是如果我们不创建一个自动释放对象该怎么办?在整个线程中,那么在这种情况下,也有必要在线程的开头创建一个自动释放池.

Apple docs suggest that we need to use them when we are using threads so in the beginning of a thread we need to create an autorelease pool and in the end of the thread drain it but what if we are not creating an autorelease object in the complete thread then in that condition also is it necessary to create an autoreleasepool in the beginning of the thread.

请清除我的困惑. 谢谢.

Please clear out my confusion. Thanx.

推荐答案

您的假设是正确的.当您可以确保特定线程永远不会使用自动释放的对象时,该线程就不需要自动释放池.

Your assumption is correct. When you can ensure a specific thread is never making use of autoreleased objects, that thread wouldn't need an autorelease pool.

避免使用自动释放池是一个坏建议,硬币有两个方面.使用自动释放的对象会带来一定的开销(尽管在大多数情况下是微不足道的),应尽可能避免这些开销.尤其是在方法有多个出口或可能遇到异常的情况下,自动释放有助于避免内存泄漏并使代码更整洁.

Avoiding the autoreleasepool is a bad advice, the coin has two sides. Using autorelease'd objects carries a certain amount of overhead (although insignificant in most scenarios) that should be avoided when possible. Especially in cases where there are multiple exits to a method, or an exception can be encountered, autoreleasing helps avoiding memory leaks and makes code cleaner.

但是请注意,这意味着该线程上的任何内容都不能使用自动释放功能,包括您可能会调用的任何框架.在某些情况下,例如在经典的生产者/消费者方案中.您有一个生产者来创建对象,将其分配到主线程runloop,然后可以在主线程autoreleasepool中注册它们.

Be aware though, that this means nothing on that thread can use autorelease, including any frameworks you may call. There are situations where this is the case, such as in a classic producer/consumer scenario. You have a producer that creates objects, dispatches them to the main threads runloop, and can register them in the main threads autoreleasepool consequently.

通常,我不建议创建一个没有自动释放池的线程,该线程会执行大量工作(除了简单,长时间运行的计算).

In general, I would not recommend creating a thread where significant work is carried out (besides a simple, long running computation) without an autoreleasepool.

这篇关于为什么要使用自动释放池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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