释放我已经完成的 NSString 会导致崩溃
请注意下面注释掉的 [printvolfirst release];
行。如果我取消注释,程序就会崩溃。我不明白为什么。除了您在此处看到的代码行之外,printvolfirst
变量不会在其他任何地方使用。将其分配给 printvol
后,我就完成了。那么为什么不释放它呢?
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];
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
stringFromNumber:
自动释放返回的对象。如果再次释放它,它会在释放后释放。事实上,您甚至不需要此代码:
您可以在构建设置中打开“运行静态分析器”以获取有关此类情况的警告。
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:
You can turn on 'Run Static Analyser' in the build settings to get warned about such things.
您正在释放一个
autorelease
d 字符串。尽管您正在执行NSString*printvolfirst=[[NSString alloc]init];
,但当您执行printvolfirst=[format stringFromNumber:[NSNumber numberWithFloat:vol] 时,您会丢失对该对象的引用];
,您可以在其中将自动释放的对象分配给printvolfirst
。在此过程中,您还造成了内存泄漏。你不必释放它。You are deallocating an
autorelease
d string. Although you are doingNSString*printvolfirst=[[NSString alloc]init];
, you are losing the reference to that object when you doprintvolfirst=[format stringFromNumber:[NSNumber numberWithFloat:vol]];
where you assign an autoreleased object toprintvolfirst
. In the process, you have also created a memory leak. You don't have to release it.