Dave
Dave

Reputation: 275

Objective-c Memory Question

I have a question regarding memory management in objective-c. I have read Apple's various documents regarding this but I still don't seem to be grasping it. I have created a small sample app to demonstrate my confusion. When I launch the app Activity Monitor states that it's using about 7MB. When I execute the main loop the memory usage goes up to 44MB which is expected. However, when I release the array I only get about 14MB back in Activity Monitor. The app continues to use about 30MB. Shouldn't I get all my memory back return the "Real Memory" to 7MB in Activity Monitor?

What am I doing wrong?

Thanks in advance.

Here is the AppDelegate:

- (IBAction) buildArray:(id)sender {
    values = [[NSMutableArray alloc] init]; // values is an instance variable of the appDelegate
    for(int i = 0; i < 500000; ++i) {
        NSString *tempString = [NSString stringWithFormat:@"New Object %i", i];
        [values addObject:tempString];
    }
    [valuesTable reloadData];  // valuesTable is a NSTableView to diplay the array.
}

- (IBAction) clearMemory:(id)sender {
    [values release];
    [valuesTable reloadData];
}

- (int) numberOfRowsInTableView: (NSTableView *) tableView {
    if (values) {
        return [values count];
    } else {
        return 0;
    }
}

- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) row {
    return [values objectAtIndex:row];
}

Upvotes: 0

Views: 80

Answers (1)

Williham Totland
Williham Totland

Reputation: 29039

This has been answered a multitude of times before; but the act of releasing an object does not immediately return memory to the system. The application holds on to parts of the arena that lie unused, waiting for them to be reallocated.

If they are actually requested by the system, it gives up these resources, but as long as no other process wants the memory, your application will hang on to it, "just in case".

Upvotes: 2

Related Questions