views:

57

answers:

2

Every time I write a new iPhone Application, I start with creating the Target, adding the frameworks, and writing this in a brand new main.m:

NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
// etc...

What is actually such a pool? What is it for? It surely doesn't protect the device when it falls in a swimming pool. But why is it there? Do I need it? Is it useful or evil? Thanks

+1  A: 

An autorelease pool is an object you can think of that captures that are said to be "autoreleased" and when the pool is drained (sent the drain message), each one of those objects in the pool is sent a -release method.

jer
So it releases all autoreleasing objects?Also, should I also use this in my Mac apps, or only my iPhone Apps?
Time Machine
This is not really true, they are not sent release messages asynchronously. All objects in the pool will be sent a release message (and potentially a dealloc message) and must return from these messages before drain will return.
Jason Coco
yeah use it in mac apps.
fernyb
@Jason, my apologies, I didn't realize I typed in async sorry; working on several things at once. I've edited it to correct that.
jer
@koning, I strongly recommend just taking a read over the class reference for NSAutoreleasePool for usage situations. For instance, there are some cases outlined in the documentation where you really need to pay attention when you use pools, etc. Suffice to say, you will use them on both mac and iphone/ipad apps, but still read the class reference.
jer
+3  A: 

A NSAutoreleasePool is responsible to handle ownerless objects and deallocate them when the pool is deallocated. I suggest you to read this documentation on the subject.

With an example:

  • You create a NSAutoreleasePool.
  • Your code is calling a method that will return an object.
  • In that method, you create an object but you don't want to keep its ownership. So you send this object an autorelease message that will say: "I don't own this object anymore". The pool now takes care of the object. Note that even if the object is not own, it is not deallocated.
  • In the calling code, you get the resulting object. As the object is still alive, you can use it.
  • When the pool is deallocated, the object will be deallocated.
Laurent Etiemble
+1 for the documentation link
Dave DeLong