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

1

73

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.

Nicosia answered 10/11, 2010 at 4:2 Comment(1)
From the answer posted by @Gustavo Ambrozio which was removed, the documentation is here, in case any viewers are interested.Lempira
N
112

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.

Negativism answered 10/11, 2010 at 5:18 Comment(3)
Not clearly enough. Documentation bug filed (<rdar://problem/8651175>).Negativism
can anyone provide the link the apple doc related to this one ? thankxLues
@Lues developer.apple.com/library/ios/DOCUMENTATION/General/… (Search for autorelease).Negativism

© 2022 - 2024 — McMap. All rights reserved.