iphone - 你需要在 GCD 的一个 block 中创建一个 NSAutoreleasePoo

通常,如果您生成后台线程或在 NSOperationQueue 上运行 NSOperation,则需要为该线程或操作创建 NSAutoreleasePool,因为默认情况下不存在。

相同的规则是否适用于放置在 Grand Central Dispatch 队列中并将在非主线程上运行的 block ?也就是说,您是否需要在您分派(dispatch)到主队列以外的任何 block 中的每个 block 中创建一个 NSAutoreleasePool?

在我有限的测试中,我没有看到控制台警告您通常会在后台线程或 NSOperations 中看到自动释放对象。但是,我似乎无法找到这方面的权威文档,所以我想知道是否有人可以指出这是在哪里说明的。

最佳答案

Does the same rule apply to a block that is placed within a Grand Central Dispatch queue and will be run on a non-main thread? That is, do you need to create an NSAutoreleasePool within each block you dispatch to anything other than the main queue?

Grand Central Dispatch 将自动管理每个队列的自动释放池。但是,无法保证池何时会被耗尽;可能是在处理一个 block 之后,也可能是在数百个(但可能不会)之后。

因此,如果您只分配几个对象,请不要担心。但是,如果您要分配大量对象(并且由于您的目标是内存受限的环境),那么您应该创建和排空池。


文档已更新。

看 https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW1

If your block creates more than a few Objective-C objects, you might want to enclose parts of your block’s code in an @autorelease block to handle the memory management for those objects. Although GCD dispatch queues have their own autorelease pools, they make no guarantees as to when those pools are drained. If your application is memory constrained, creating your own autorelease pool allows you to free up the memory for autoreleased objects at more regular intervals.

关于iphone - 你需要在 GCD 的一个 block 中创建一个 NSAutoreleasePool 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4141123/

相关文章:

ios - 找不到符号 : kUTTypeImage

ios - 如何为 NSDate 添加一个月?

objective-c - 整数总是初始化为0吗?

objective-c - 在 Objective-C 中从字符串中删除空格

objective-c - 删除 NSString 的最后一个字符

ios - NSPredicate 用于测试 NULL 和空白字符串

ios - 在主线程上调用方法?

iphone - 实现 copyWithZone : 时的最佳实践

ios - 是否可以调试 "Terminated due to memory error"?

iphone - iOS 7 UIRefreshControl tintColor 不适用于 beg