user142019
user142019

Reputation:

What is a autorelease pool in Foundation Kit?

Every time I write a new iOS 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?

Upvotes: 1

Views: 137

Answers (2)

jer
jer

Reputation: 20236

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.

Upvotes: 1

Laurent Etiemble
Laurent Etiemble

Reputation: 27889

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.

Upvotes: 4

Related Questions