@autoreleasepool语义 [英] @autoreleasepool semantics

查看:78
本文介绍了@autoreleasepool语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在llvm网站上阅读ARC文档: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#autoreleasepool

..尤其是有关@autoreleasepool的信息.

在许多当前使用NSAutoreleasePool的实现中,我看到在循环迭代期间池定期被排空的情况-我们如何使用@autorelease池来做同样的事情,还是全部在幕后为我们完成? >

第二,文档指出如果引发异常,则不会耗尽该池....好的异常在名称上是特殊的,但是如果确实发生,则您可能希望在不泄漏内存的情况下进行恢复.文档未指定何时释放这些对象.

有人知道这些点的任何信息吗?

解决方案

在许多当前使用NSAutoreleasePool的实现中,我看到在循环迭代期间池定期被排空的情况-我们如何使用@autorelease池来做同样的事情,还是全部在幕后为我们完成? >

以相同的方式,即通过级联自动释放池.例如:

@autoreleasepool {
    …
    for (int i = 0; i < MAX; i++) {
        @autoreleasepool {
            …
        }
    }
    …
}

第二,文档指出如果引发异常,则不会耗尽该池....好的异常在名称上是特殊的,但是如果确实发生,则您可能希望在不泄漏内存的情况下进行恢复.文档未指定何时释放这些对象.

在大多数情况下,由于可可中异常的特殊性质,程序无法正常恢复,因此我想说泄漏对象的问题较小.如果由于异常而退出了@autoreleasepool块,则仅当弹出其中一个封闭的自动释放池时,相应的自动释放对象才会被释放.但是,您当然可以将@try/@catch/@finally块放置在@autoreleasepool块内,以防止发生这种情况.

I was reading the ARC docs on the llvm site: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#autoreleasepool

..in particular about @autoreleasepool.

In lot of current implementation using NSAutoreleasePool, I see cases where the pool is drained periodically during a loop iteration - how do we do the same with @autorelease pool, or is it all done for us somehow under the hood?

Secondly, the docs state that if an exception is thrown, the pool isn't drained.... ok exceptions are by name exceptional, but if they do happen, you might like to recover without leaking a load of memory. The docs don't specify when these objects will be released.

Anyone got any info about these points?

解决方案

In lot of current implementation using NSAutoreleasePool, I see cases where the pool is drained periodically during a loop iteration - how do we do the same with @autorelease pool, or is it all done for us somehow under the hood?

In the same way, i.e., by cascading autorelease pools. For instance:

@autoreleasepool {
    …
    for (int i = 0; i < MAX; i++) {
        @autoreleasepool {
            …
        }
    }
    …
}

Secondly, the docs state that if an exception is thrown, the pool isn't drained.... ok exceptions are by name exceptional, but if they do happen, you might like to recover without leaking a load of memory. The docs don't specify when these objects will be released.

In most cases the program won’t be able to recover gracefully due to the peculiar nature of exceptions in Cocoa, so I’d say that leaking objects is a lesser problem. If an @autoreleasepool block is exited because of an exception, the corresponding autoreleased objects will only get released when one of the enclosing autorelease pools is popped. But you can, of course, place @try/@catch/@finally blocks inside the @autoreleasepool block to prevent this from happening.

这篇关于@autoreleasepool语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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