2011-03-25 181 views
2

我是iphone開發人員和處理內存問題的新手。 我在學習,但有些東西對我來說依然神祕。內存泄漏問題

在以下情況下,「Instruments」的泄漏分析器說我在databasePath設置中存在泄漏。我無法弄清楚爲什麼。

// databaseName and databasePath are properties of my class. 
databaseName = [[NSString alloc] initWithString:@"sqlDbName.sql"]; 

NSArray *documentPaths = [[NSArray alloc] initWithArray:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)]; 

NSString *documentsDir = [[NSString alloc] initWithString:[documentPaths objectAtIndex:0]]; 

// The problem is here : 
databasePath = [[NSString alloc] initWithString:[documentsDir stringByAppendingPathComponent:databaseName]]; 

[documentPaths release]; 
[documentsDir release]; 

我稍後在dealloc中釋放databaseName和databasePath。

您的幫助將非常感謝!

+0

你的意思是你釋放'databasePath'和'databaseName'在你的dealloc方法中(你的最後一段說'databasePath'兩次)? – Rog 2011-03-25 09:59:04

+0

在dealloc中我釋放databasePath和databaseName,沒錯。 – 2011-03-25 10:41:39

回答

5

是否有任何可能性,此代碼正在執行多次。您已在dealloc中發佈databasePath。如果這個代碼被執行多次,那麼databasePath會泄漏任何連續的執行。

+0

是的!你統治。該方法被調用兩次。我修好了,沒有更多的泄漏出現。非常感謝。 – 2011-03-25 10:45:42

+0

只是一個問題:如何在此論壇上標記「解決」我的答案? – 2011-03-25 10:48:54

+0

您選擇的問題左側的複選框爲答案,只需點擊它,它就會變成綠色:) – Rog 2011-03-25 10:52:08

1

如果你確實想有這個方法調用了兩次,你可以這樣做:

... 
[databasePath release]; 
databasePath = [[NSString alloc] initWithString:[documentsDir stringByAppendingPathComponent:databaseName]]; 
.... 

如果databasePath最初是零調用[databasePath release];不會做任何事情。

如果databasePath已經初始化,它將在確定新實例之前釋放舊的實例。

+0

謝謝,這將會有所幫助。 – 2011-03-28 07:44:08