views:

92

answers:

2

Why would you drain an autorelease pool instead of releasing it?

+5  A: 

One reason is for garbage collection (not available on iPhone)

release is a no-op with GC enabled, but drain provides a hint to the garbage collector

From the docs:

Garbage Collection

In a garbage-collected environment, there is no need for autorelease pools. You may, however, write a framework that is designed to work in both a garbage-collected and reference-counted environment. In this case, you can use autorelease pools to hint to the collector that collection may be appropriate. In a garbage-collected environment, sending a drain message to a pool triggers garbage collection if necessary; release, however, is a no-op. In a reference-counted environment, drain has the same effect as release. Typically, therefore, you should use drain instead of release.

cobbal
Way back in the day, drain and release were separate. You had to call drain and then release. However, since you always drained then released they just combined to drain. I think they kept the drain because manual memory management used to be very important and you need to be able to spot exactly where the pool drained in code.
TechZen
Er, what? `-drain` was added in the 10.4 SDK, specifically for the reason of garbage collection compatibility. (Garbage collection was not available in 10.4, but some of the groundwork had been done.) It had to be done this way because it is impossible to override `-release` in GC.
Ahruman
This is a bad answer in the context of the iPhone. See my answer for a better reason to use `drain`.
St3fan
@TechZen: That's a Cocoa urban legend. As Ahruman noted, `drain` was added in 10.4 as a synonym for `release`. The reason for the two synonymous methods is that Apple's implementation of GC renders `release` a no-op, so they needed to use a different selector if they wanted the method to work both in GC and MM environments.
Chuck
A: 

The best answer here is "because Apple tell you to".

Following Apple's "best practices" is the best way to improve your chances of being forward compatible.

Jeff Laing