Hello all,
I am developing a program in Cocoa, with the hopes of using the smallest amount of memory possible. To check this, I have been using Activity Monitor. My program has a fairly large NSMutableArray
containing instances of NSString
, and when I release the array, I do not get all of my memory back. The following example demonstrates my problem.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:10];
NSLog(@"The array has no elements!"); // Activity monitor says 1.5 megs
[NSThread sleepForTimeInterval:10];
NSUInteger i;
for(i = 0;i < 1000000;i++)
{
NSString *str = [[NSString alloc] initWithFormat:@"Number=%d, again it is: %d, one more time for added length: %d", i, i, i];
[array addObject:str];
[str release];
}
NSLog(@"We have used lots of memory!"); // Activity Monitor says 108 megs
[NSThread sleepForTimeInterval:5];
[array release];
NSLog(@"We have released the array!"); // Activity Monitor says 19 megs
[NSThread sleepForTimeInterval:5];
[pool drain];
NSLog(@"We have drained the pool!"); // Activity Monitor still says 19 megs
[NSThread sleepForTimeInterval:5];
return 0;
}
I added calls to sleepForTimeInterval
so I could see and note the memory usage listed by Activity Monitor. At each pause I have listed the amount of memory I am supposedly using. I am almost sure my problem stems from a misunderstanding in the retain/release conventions. Does anyone see where I am going wrong?