Why does this program take up so much memory?
- by Adrian
I am learning Objective-C. I am trying to release all of the memory that I use. So, I wrote a program to test if I am doing it right:
#import <Foundation/Foundation.h>
#define DEFAULT_NAME @"Unknown"
@interface Person : NSObject
{
NSString *name;
}
@property (copy) NSString * name;
@end
@implementation Person
@synthesize name;
- (void) dealloc {
[name release];
[super dealloc];
}
- (id) init {
if (self = [super init]) {
name = DEFAULT_NAME;
}
return self;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Person *person = [[Person alloc] init];
NSString *str;
int i;
for (i = 0; i < 1e9; i++) {
str = [NSString stringWithCString: "Name" encoding: NSUTF8StringEncoding];
person.name = str;
[str release];
}
[person release];
[pool drain];
return 0;
}
I am using a mac with snow leopard. To test how much memory this is using, I open Activity Monitor at the same time that it is running. After a couple of seconds, it is using gigabytes of memory. What can I do to make it not use so much?