James Richard James Richard - 8 months ago 75
Objective-C Question

Autorelease pools and when release is called under iOS

I wanted to get something clarified.

Lets say I have the following code:

- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
for (int i = 0; i < 5000000; i++) {
NSString *s = [NSString stringWithFormat:@"Hello, %@!", @"World"];

This will create 5 million autoreleased strings within this function call. I was expecting this to keep those objects around until the termination of the application, as the only @autoreleasepool I see is the one wrapping the application instantiation in main.m. That's not the case, though. At the end of this function call, it seems they all get their release called and are removed from memory.

This document:


States that "The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event."

That makes sense to me, but this is under UIKit, and not Application Kit. My question is, does UIKit/Cocoa Touch do the same thing in this case, or is there another explanation for my objects getting released?



Yes, UIKit does the same thing. The system-created, main thread autorelease pool is drained at the end of every run loop cycle. It's probably best not to rely on this exact lifetime in your own code. If you create a new thread manually (using e.g. NSThread), you're responsible for creating the autorelease pool on that thread.

EDIT: Rob's answer provides some good additional information regarding behavior under ARC. In general, it's fair to say that objects are less likely to end up in the autorelease pool due to some optimizations ARC is able to make.