为什么使用自动释放池?

发布于 2024-11-15 22:41:02 字数 287 浏览 2 评论 0原文

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

但人们总是说要避免自动释放对象,以避免内存泄漏并进而导致应用程序崩溃。

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

苹果文档建议我们在使用线程时需要使用它们,因此在线程开始时我们需要创建一个自动释放池,并在线程结束时耗尽它,但是如果我们没有完整地创建自动释放对象怎么办?那么在这种情况下,线程还需要在线程的开头创建一个自动释放池。

请解开我的困惑。 谢谢。

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.

Then why and in which conditions should we use autoreleasepool?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温馨耳语 2024-11-22 22:41:02

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

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

但请注意,这意味着该线程上的任何内容都不能使用自动释放,包括您可能调用的任何框架。在某些情况下会出现这种情况,例如在经典的生产者/消费者场景中。您有一个生产者,它创建对象,将它们分派到主线程运行循环,并可以将它们注册到主线程自动释放池中。

一般来说,我不建议创建一个在没有自动释放池的情况下执行重要工作(除了简单、长时间运行的计算之外)的线程。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文