5

我想要一個快速簡單的方法從URL獲取數據,而不必與delegates混淆。GCD dispatch_async和NSURLConnection

以下有什麼不對嗎?

// Use gcd 
dispatch_queue_t queue = dispatch_queue_create("com.dowork", 0); 
dispatch_queue_t main = dispatch_get_main_queue(); 

// do the long running work in bg async queue 
// within that, call to update UI on main thread. 
dispatch_async(queue, ^{ 

    // Do work in the background 
    NSData *response = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError]; 

    dispatch_async(main, ^{ 

     // Update UI 
     self.data = response; 
     [self.tableView reloadData]; 


    });//end 
});//end 

我想我讀的地方很久以前,在一個後臺線程使用NSURLConnection同步方法將導致內存泄漏。這是真的?

這裏發佈的代碼有問題嗎?在塊內將數據分配給self.data的任何問題?

回答

4

如果你的目標的iOS5及更高版本,有NSURLConnection的的sendAsynchronousRequest:queue:completionHandler:

爲了回答您的具體問題,它看起來對我來說,response可能泄漏:我不知道是否有關於GCD線程隱式自動釋放池。

現在就完成一些研究:GCD線程擁有自己的autorelease池,但不知道它們何時會被耗盡。你可能想用明確的自動釋放池括起前兩個語句。

另請參見Do you need to create an NSAutoreleasePool within a block in GCD?

+0

我意識到這一點,並用它測試了一些實現。但是,我需要做的事情仍然有限。我上面展示的方法非常好,並且很容易獲得'NSData',所有其他異步方法似乎都是代理的2步過程。所以,仍然想知道我最初的問題。 – 2012-02-23 09:56:56

+0

@Nic:更新我的回答 – JeremyP 2012-02-23 10:03:18

+0

謝謝,所以你認爲這樣做是安全的,只要我添加自己的autorelease池? – 2012-02-23 10:06:24