2012-07-30 74 views
0

這段代碼給我一個100次迭代100次以上的泄漏。如果我寫[imageName發佈]它崩潰與「發送到釋放實例的消息」。我甚至不能想到什麼是問題的根源。奇怪的NSString泄漏

NSString* imageName=[NSString stringWithUTF8String:(const char*)sqlite3_column_text(statement, 5)]; 
imageName =[imageName stringByReplacingOccurrencesOfString:@"-" withString:@"_"]; 
imageName =[imageName stringByReplacingOccurrencesOfString:@"." withString:@"-"]; 

[ret setQuestionImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"]]]; 
+0

「ret」從哪裏來?你有每個迭代新的?他們都呆在附近嗎?如果您保留100張JPEG圖像,則容易達到100 MB。 – Thilo 2012-07-30 10:17:40

+0

ret是爲每次迭代動態創建的,我每次都釋放它 – 2012-07-30 10:19:41

回答

3

問題是由這些便利方法創建的字符串和圖像是自動釋放的,並且自動釋放不會及早發生。但是,如果你明確地釋放它們,它們將在autorelease時被雙重釋放。嘗試將所有迭代包裝到自動釋放池中:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
NSString *imageName=[NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 5)]; 
imageName = [imageName stringByReplacingOccurrencesOfString:@"-" withString:@"_"]; 
imageName = [imageName stringByReplacingOccurrencesOfString:@"." withString:@"-"]; 

[ret setQuestionImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"]]]; 
[pool release]; 
+0

另外,如果您稍微改進了整體編碼/縮進樣式,那將有助於使代碼更具可讀性。 :) – 2012-07-30 10:21:12

+0

謝謝!那麼,問題是在糟糕的dealloc「ret」對象:) – 2012-07-30 10:28:40