2011-03-31 20 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.