2010-08-20 65 views
1
// Create the request. 
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] 
         cachePolicy:NSURLRequestUseProtocolCachePolicy 
        timeoutInterval:60.0]; 
// create the connection with the request 
// and start loading the data 
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
if (theConnection) { 
    // Create the NSMutableData to hold the received data. 
    // receivedData is an instance variable declared elsewhere. 
    receivedData = [[NSMutableData data] retain]; 
} else { 
    // Inform the user that the connection failed. 
} 

既然我們不通過調用retain來擁有receivedData,我們不是在泄漏內存嗎?Apple NSURLConnection文檔是否錯誤?

什麼時候你應該釋放連接並收到數據?

回答

1

1 /關於連接,我們使用委託模式來處理這種內存管理。你用一種方法分配init並設置委託。然後當你喜歡的連接回調:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    [connection release]; 
} 

或者你可以在任何其他委託方法釋放連接。這是他們將你連接回去的原因之一。你會遇到這種委託模式很多iPhone一樣的UIImagePickerController(只是另一個例子),尤其是在網絡問題時,你必須等待,直到網絡完成釋放

2 /從評論,

// Create the NSMutableData to hold the received data. 
// receivedData is an instance variable declared elsewhere. 

所以,這很容易回答,因爲receivedData是一個實例變量,您應該可以在dealloc方法中釋放它。另一種選擇是爲它聲明一個@property (nonatomic, retain),然後它將確保沒有內存泄漏,如果你多次設置receivedData

0

此代碼擁有連接和數據。連接是使用alloc/init創建的,稍後需要發佈,數據將保留,因此也需要發佈。

+0

你在哪裏發佈? – 2010-08-20 22:30:07

+1

完成加載後釋放連接。無論是在連接完成加載或連接確實失敗,錯誤。完成後釋放數據。只有你可以知道你什麼時候做完了。基本的內存管理原則。 – Jasarien 2010-08-20 23:32:40