Releasing an NSString that I am done with causes a crash
Note the commented-out [printvolfirst release];
line below. If I un-comment it, the program crashes. I can't figure out why. The printvolfirst
variable is not used anywhere else except in the lines of code you see here. After it is assigned to printvol
I'm done with it. So why not release it?
vol = vol / 1000000;
NSNumberFormatter * format = [[NSNumbe开发者_如何学CrFormatter alloc] init] ;
[format setPositiveFormat:@"#.#"];
NSString * printvolfirst = [[NSString alloc]init];
printvolfirst = [format stringFromNumber:[NSNumber numberWithFloat:vol]];
NSString * printvol = [[NSString alloc] initWithFormat: @"%@M", printvolfirst];
self.Pop.vol.text = printvol;
[printvol release];
//[printvolfirst release];
[format release];
stringFromNumber:
autoreleases the returned object. If you release it again, it's released after it has been deallocated.
In fact, you don't even need this code:
NSString*printvolfirst=[[NSString alloc]init];
You can turn on 'Run Static Analyser' in the build settings to get warned about such things.
You are deallocating an autorelease
d string. Although you are doing NSString*printvolfirst=[[NSString alloc]init];
, you are losing the reference to that object when you do printvolfirst=[format stringFromNumber:[NSNumber numberWithFloat:vol]];
where you assign an autoreleased object to printvolfirst
. In the process, you have also created a memory leak. You don't have to release it.
精彩评论