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

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.

Leave a Comment