Reputation: 7504
I read about NSAutoReleasePool and understand that it makes memory management easier on iPhone. It is available on NSObject so autorelease message available for every object instance. Moreover, I shouldn't use autorelease a lot as NSAutoReleasePool uses cache memory and you might runout of memory if there are plenty autoreleased objects. Is my understanding correct?
One thing I didn't understand is what is the purpose of creating NSAutoreleasePool explicitly like it's done in following method? What its purpose here? Is it like releasing imgData, img objects automatically? Because I could see that these objects are not released in this method.
- (void)loadImage {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage *img = [UIImage imageNamed: @"default_user.png"];
if(![[imgURL absoluteString] isEqualToString: @"0"]) {
NSData *imgData = [NSData dataWithContentsOfURL: imgURL];
img = [UIImage imageWithData: imgData];
}
if([target respondsToSelector: action])
[target performSelectorOnMainThread: action withObject: img waitUntilDone: YES];
[pool release];
}
Thanks.
Upvotes: 0
Views: 184
Reputation: 12405
The idea behind auto-release to keep the memory usage of the app low. You see if you haven't used this auto release then this data would have gone to the main autorelease of the app So even if you don't need this image further it still stays in the memory and increases its footprint. Creating a new auto release frees the memory straight away.(the size of the image can be huge.)
Upvotes: 1
Reputation: 29767
You can use local autorelease pools to help reduce peak memory footprint. When your pool is drained, the temporary objects are released, which typically results in their deallocation thereby reducing the program’s memory footprint.
I can suggest this explicit autorelease pool was created for manage image loading. Probably that image has a large size (in Mb) and this pool can guarantee that memory will released asap. All autorelease pools organized in stack, so this inner pool will drain early than main pool.
Upvotes: 3
Reputation: 815
The rule is that you must create an autorelease pool in every thread that will use autorelease. In your example, img
variable is autoreleased, and assuming the loadImage
method is threaded, you must declare a new pool before using any autoreleased memory.
Upvotes: 0