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
的任何問題?
我意識到這一點,並用它測試了一些實現。但是,我需要做的事情仍然有限。我上面展示的方法非常好,並且很容易獲得'NSData',所有其他異步方法似乎都是代理的2步過程。所以,仍然想知道我最初的問題。 – 2012-02-23 09:56:56
@Nic:更新我的回答 – JeremyP 2012-02-23 10:03:18
謝謝,所以你認爲這樣做是安全的,只要我添加自己的autorelease池? – 2012-02-23 10:06:24