I've written some Objective-C
application that seems to work fine, except for an ever-growing memory footprint. I'm using ARC under the last version of Xcode 4.6.2. My system is 10.7.5.
I'm very new to Objective-C
and need some help figuring out what's going on with my memory. I've narrowed down the problem to explaining why the following basic piece of code behaves like it does.
This code is added in the vanilla Cocoa-based application template that Xcode gives (ARC enabled).
Case A
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
NSDate* d;
for(int i=0; i<1000000; i++){
d = [[NSDate alloc] init];
}
}
Everything goes as expected, ARC reclaims the memory on the fly. Namely, the memory usage history is very flat. When the for loop ends, the app takes about 25MB memory.
Case B
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
NSDate* d;
for(int i=0; i<1000000; i++){
d = [NSDate date];
}
}
Here things are really mysterious to me. When just running the app, the (real) memory usage keeps increasing to about 53MB and then stays there, forever.
However, when running the allocations profiler tool, I can see that at the end of the for loop, all the objects are deallocated, very much like you would expect with an autorelease pool. Also, enclosing the body of the for loop with an @autoreleasepool{} makes case B behave like case A (as expected).
So, three questions:
- Under ARC, what is the difference between using the "autoreleased"
[NSDate date]
and the alloc init object? (I thought there would be close to none from other questions here.) - Why doesn't ARC seem to kick in when running the code?
- Why is there a difference in the memory behavior of the profiled application and the actual application?