I’m new to Objective-C and I’m not sure if I’m using NSAutoreleasePool the right way.
-
If I want to use autorelease only one time I use:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *newText = [NSString stringWithFormat:@"%d", prograssAsInt]; sliderLabel.text = newText; [pool release]; //newText will be released -
If I want to use autorelease several times I use:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *newText = [NSString stringWithFormat:@"%d", prograssAsInt]; sliderLabel.text = newText; [pool drain]; //newText will be released newText = [NSString stringWithFormat:@"%d", prograssAsInt]; sliderLabel.text = newText; [pool drain]; //newText will be released newText = [NSString stringWithFormat:@"%d", prograssAsInt]; sliderLabel.text = newText; [pool release]; //newText will be released
Is this OK? Are there any memory leaks?
(2) is not OK.
-drainand-releaseare equivalent (in a ref-counting environment), and aftering-draining the autorelease pool is deallocated. So you will double-release the autorelease pool object and crash the program.Even before ARC, unless you are working in a very tight memory budget, it’s atypical to create an NSAutoreleasePool besides the boilerplate
main(). The objects-autoreleased into the pool will be released after every tick of NSRunLoop anyway. There will be no memory leak if you strictly follow the ownership transfer rules (see Understanding reference counting with Cocoa and Objective-C).And with ARC turned on you don’t even need to care about this — the compiler will insert the
-retainand-releaseat the right place for you.Also, if
sliderLabel.textis marked as@property(retain)(or(strong)), then releasing the autorelease pool in (1) will not release the newText because that object has a new owner now.