开发者

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 autoreleased 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜