Do you need to create an NSAutoreleasePool within a block in GCD?

Brad Larson picture Brad Larson · Nov 10, 2010 · Viewed 10.9k times · Source

Normally, if you spawn a background thread or run an NSOperation on an NSOperationQueue you need to create an NSAutoreleasePool for that thread or operation because none exists by default.

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?

In my limited testing, I don't see the console warnings for autoreleased objects that you normally see with background threads or NSOperations. However, I can't seem to find definitive documentation on this, so I was wondering if someone could point out where this is stated.

Answer

bbum picture bbum · Nov 10, 2010

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 will manage an autorelease pool per queue automatically. However, there are no guarantees as to when the pool will be drained; it may be after one block is processed, it may be after hundreds (but probably won't be).

So, if you are only allocating a few objects, don't worry about it. However, if you are allocating any significant number of objects (and since you are targeting a memory constrained environment), then you should be creating and draining pools.


The documentation has been updated.

See 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.