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