views:

74

answers:

2

Im new to obj-c and have trouble understanding the function autorelease. could someone explain to me when i should use it? and how is it different than release. also do I need to reset the autorelease pool? how? and when?

A: 

When you send -autorelease to an object, it's added to a list (the autorelease pool), and when the pool is released or drained, every object in the list gets a -release message.

Autorelease is nothing but a delayed message mechanism.

NSResponder
+2  A: 

Calling autorelease schedules a release message to be sent to an object sometime in the near future by adding the object to the topmost NSAutoreleasePool. When a pool receives the drain message, it sends release to all the objects that have been added to it.

autorelease is used in situations where a method or function needs to relinquish its ownership of an object, but needs to keep it from being deallocated temporarily so that its caller can do something with it. It's also useful in creating "convenience" methods that wrap alloc, initWith... and autorelease to make code that allocates objects simpler.

rpetrich
so I need to drain NSAutoreleasePool manually right? this is not garbage collection? when should i call the drain method?
Yazzmi
You do not need to drain the main NSAutoreleasePool, it will garbage collect. However, if you create your own NSAutoreleasePool you need to release that yourself. In case you have some code that is allocating a lot of autoreleased objects (lots of memory), you can drain the pool to free that memory instantly when it's no longer needed. If that is the case, you should set up a new NSAutoreleasePool for this scenario and drain that instead of draining the main/application pool.
Merrimack
It's not true that it will garbage collect--the iPhone does not have garbage collection at all. The system does, however, create a pool before dispatching an event from the main runloop and drain it after the event has finished processing.
rpetrich