释放我已经完成的 NSString 会导致崩溃

发布于 2024-11-14 11:36:34 字数 632 浏览 2 评论 0原文

请注意下面注释掉的 [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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

为你拒绝所有暧昧 2024-11-21 11:36:34

stringFromNumber: 自动释放返回的对象。如果再次释放它,它会在释放后释放。

事实上,您甚至不需要此代码:

NSString*printvolfirst=[[NSString alloc]init];

您可以在构建设置中打开“运行静态分析器”以获取有关此类情况的警告。

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.

命硬 2024-11-21 11:36:34

您正在释放一个 autoreleased 字符串。尽管您正在执行 NSString*printvolfirst=[[NSString alloc]init];,但当您执行 printvolfirst=[format stringFromNumber:[NSNumber numberWithFloat:vol] 时,您会丢失对该对象的引用];,您可以在其中将自动释放的对象分配给 printvolfirst。在此过程中,您还造成了内存泄漏。你不必释放它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文