Object References and the Autorelease Pool

You might need to write a method that first creates an object (say with alloc) and then returns that object as the result of the method call. Here’s the dilemma: Even though the method is done using the object, it can’t release it, because it needs to return its value. The NSAutoreleasePool class was created in order to help solve problems like these by keeping track of objects to be released at a later time in an object known as an autorelease pool. That later time is when the pool gets drained, which is done by sending the autorelease pool object a drain message.

To add an object to the list of objects maintained by the autorelease pool, you send that object an autorelease message, like so:

[result ...

Get Programming in Objective-C, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.