何时释放 UIImage 和 NSString 资源
我试图让我的内存管理正确,在下面的代码中,如果我包含最终的释放语句(文件路径的那个),它会崩溃,我不明白为什么。我已经分配了它,为什么不应该释放它呢?
再往下,我将 cellAbout 返回到 TableView。
有人可以解释一下吗?
UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2];
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
filePath = [filePath stringByAppendingString:@".png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath];
imageView.image = image;
[image release];
[filePath release];
非常感谢,
克里斯。
I'm trying to get my memory management right and in the code below, if I include the final release statement (the one for filePath), it crashes and I can't see why. I've alloc'ed it, so why shouldn't I release it?
Further down, I return cellAbout to the TableView.
Can someone explain?
UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2];
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
filePath = [filePath stringByAppendingString:@".png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath];
imageView.image = image;
[image release];
[filePath release];
Many thanks,
Chris.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
答案是原始 filePath 字符串已分配并需要释放,但是当您有以下行:
您创建了一个不同的字符串时 - 指向 filePath 的原始指针现在消失了并且是泄漏。
这是您真正想要的代码
所以您不需要释放 filePath - 它是自动释放的。苹果还特别呼吁添加路径扩展。
实际上,这就是大多数人编写代码的方式——少一行。
The answer is that the original filePath string IS alloced and needs to be released, but when you have the line:
you create a different string - the original pointer to filePath is now gone and is a leak.
Here is the code you actually want
So you don't need to release the filePath - it is auto released. Also apple has a special call for adding path extensions.
is actually how most people would write that code - one fewer lines.
您的问题
此行后泄漏 filePath。
在该行之后释放一个自动释放的对象。
相反
Your Issues
Leaking filePath after this line.
Releasing an autoreleased object after this line.
Instead
[NSString stringByAppendingString]
返回一个新字符串,因此这就是您泄漏旧字符串的地方。然后 filePath 就不再属于你了,所以当你稍后释放它时,你就会崩溃。
你可以像这样回避整个事情:
[NSString stringByAppendingString]
returns a NEW string, so that's where you're leaking your old one.And then filePath is no longer owned by you, so when you release it later, you crash.
You could sidestep this whole thing like this:
您在这里泄漏并稍后释放自动释放的字符串:
如果您确实想手动释放,请保存指针:
You are leaking here and later releasing an autoreleased string:
If you really want to manually release, save the pointer: