- Java Garbage Collection
- Objective-C Retain/Release
- etain Count
- The autorelease pool
- Conclusion
The autorelease pool
Although the retain/release strategy discussed here works in most situations that a developer is likely to encounter, it does not cover one area of particular importance. In the situation in which a method creates an object but does not want to retain control over that object, retain/release is insufficient. In addition, if the developer needs to release a large number of objects all at once, retain/release by itself does not solve this issue either.
Both of these situations are neatly solved by using an autorelease pool, which is designed to keep a reference to objects that are temporary in nature and call release on them at some later time. In a Cocoa application, for instance, an autorelease pool is already instantiated as part of the base shared application. That pool is automatically "flushed" during each event cycle.
Take for example, this snippet of code:
- (NSString *)formattedName { NSString *initString = [[NSString alloc] initWithFormat:@"[%@]", name]; [initString release]; //We do not want to retain this object return initString; }
In this example, the method is attempting to release the NSString it just created to avoid a potential memory leak. However, by releasing the object prior to returning it, the object will be deallocated before it reaches the calling object. This will produce an error.
To avoid this error, use the autorelease pool instead:
- (NSString *)formattedName { NSString *initString = [[NSString alloc] initWithFormat:@"[%@]", name]; [initString autorelease]; return initString; }
In this example, instead of releasing the NSString immediately, we are adding it to the autorelease pool, which will cause a release message to be sent to the object at some future point. This gives the calling object an opportunity to either finish utilizing the object or to call retain on the object itself.
If needed, it is possible to create additional autorelease pools that can be controlled by the developer. This is particularly advantageous in the situation of processing large amounts of data where you do not want your application to consume huge amounts of memory. By autoreleasing objects and then periodically flushing the pool, memory consumption can be controlled.