2011-06-08 47 views
2

潛在的內存泄漏我跑我的代碼「分析」,結果顯示了我的代碼以下部分潛在的內存泄漏目標C:在代碼

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; 

//Potential memory leak in code below 
[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

我不知道如何制止這種泄漏。我試圖在後面添加一個'autorelease',但是這導致了崩潰。有任何建議嗎?

編輯:

截圖泄漏消息

enter image description here

回答

2

您來電的Alloc上NSURLConnection的用的1.您的代碼的引用計數返回一個對象應該是如下:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
[connection start]; // This is optional. It should begin the request after you alloc it 

你這個對象後,需要顯式調用:

[connection release]; 
4

推出上成功或失敗的連接對象的。它需要活到那時。因此,在connection:didFailWithError:connectionDidFinishLoading:委託方法中都放了一個版本。只有一個會被調用。所以保留釋放將平衡。

+0

喜Deepak,我做了你的建議,並在委託方法中添加了連接釋放。不過,我仍然收到內存泄漏消息。我用截圖更新了我的查詢。謝謝! – Zhen 2011-06-08 03:55:44

+0

儘管您創建連接對象,但不會啓動連接。可以使用'initWithRequest:delegate:startImmediately:'並設置'startImmediately:YES'或將該對象賦值給一個變量,然後調用'start'。 – 2011-06-08 04:00:25

1

使用靜態方法

[NSURLConnection connectionWithRequest:request delegate:self]; 

,而不是

[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

當然沒有必要在它的委託方法中釋放連接對象。

或者,如果您使用第二種方法,釋放NSURLConnection的物體在兩個委託方法:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

,可以忽略內存泄漏警告消息。