开发者

When is memory actually freed in Objective-C?

I'm trying to understand memory management stuff in Objective-C. If I see the memory usage listed by Activity Monitor, it looks like memory is not being freed (I mean column rsize). But in "Object Allocations" everything looks fine. Here is my simple code:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


NSInteger i, k=10000;
while (k>0) {
    NSMutableArray *array = [[NSMutableArray alloc]init];

    for (i=0;i<1000*k; i++) {
        NSString *srtring = [[NSString alloc] initWithString:@"string...."];
        [array addObject:srtring];
        [srtring release];
        srtring = nil;
    }

    [array release];
    array = nil;
    k-=500;

}

[NSThread sleepForTimeInterval:5];
[pool release];

return 0;
}

As for retain and release it开发者_运维百科's cool, everything is balanced. But rsize decreases only after quitting from this little program. Is it possible to "clean" memory somehow before quitting?


No point in trying to scrub the memory before quitting; you're quitting, so any sparse resources you own are returned to the system.

A common misconception is that free() (the underlying mechanic for release) returns memory to the system immediately; it doesn't in most implementations, but rather adds it to an internal free list; on which the memory is kept around for your application to use, but liberated to the system if asked for. The second time your loop rolls around, your application reuses this free memory to allocate from rather than requesting more from the system, making everything smoother for everybody.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜