johnbakers
johnbakers

Reputation: 24770

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 = [[NSNumberFormatter 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];

Upvotes: 0

Views: 127

Answers (2)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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.

Upvotes: 1

user142019
user142019

Reputation:

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.

Upvotes: 4

Related Questions