2011-03-31 21 views
0

我试图让我的内存管理权限,并在下面的代码中,如果我包括最终版本声明(filePath的),它崩溃,我看不出为什么。我已经分配了它,为什么我不能释放它?何时发布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]; 

非常感谢,

克里斯。

+1

一般要找到你可能有内存管理问题,尝试在Xcode中“建立与分析”选项。它报告可疑问题。 – Dolbz 2011-03-31 12:30:00

回答

1

答案是,原来的文件路径字符串是alloced和需要被释放,但是当你有行:创建

filePath = [filePath stringByAppendingString:@".png"]; 

不同的字符串 - 指向filePath的原始指针现在消失了,并且是泄漏。

下面是代码你真的想

NSString *filePath = self.gem.poiType; 
filePath = [filePath stringByAppendingPathExtension:@"png"]; 
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath]; 
imageView.image = image; 
[image release]; 

所以你不需要发布的文件路径 - 它是自动释放。此外,苹果还特别呼吁添加路径扩展。

NSString *filePath = [self.gem.poiType stringByAppendingPathExtension:@"png"]; 

实际上大多数人会如何编写该代码 - 少一行。

+0

谢谢Tom,Till,ssteinberg和Mike。这现在非常清楚。漏洞来自filePath = [filePath ...结构,我不需要释放由stringByAppending等创建的任何东西,因为它们是自动发布的。 – Chris 2011-04-01 12:11:57

1

您在这里漏水,后来释放了自动释放字符串:

filePath = [filePath stringByAppendingString:@".png"]; 

如果你真的想手动释放,保存指针:

NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType]; 
NSString *somestring = [filePath stringByAppendingString:@".png"]; 
[filePath release]; 
1

你的问题

UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2]; 
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType]; 

泄漏此行后面的filePath。

filePath = [filePath stringByAppendingString:@".png"]; 
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath]; 
imageView.image = image; 
[image release]; 

在此行后面释放自动释放的对象。

[filePath release]; 

相反

UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2]; 
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType]; 
NSString *extendedFilePath = [filePath stringByAppendingString:@".png"]; 
[filePath release]; 
UIImage *image = [[UIImage alloc] initWithContentsOfFile: extendedFilePath]; 
imageView.image = image; 
[image release]; 
1

[NSString stringByAppendingString]返回一个新的字符串,所以这就是你泄漏你的旧字符串的地方。

然后filePath不再归您所有,所以当您稍后释放它时,就会崩溃。

你可以回避这个整个事情是这样的:

NSString *filePath = [NSString stringWithFormat:@"%@.png",self.gem.poiType];// don't release me.