我想要一种快速简便的方法来从URL
获取数据,而不必弄乱delegates
。
以下内容有问题吗?
// 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
有任何问题吗? 最佳答案
如果您的目标是ios5及更高版本,则可以使用NSURLConnection的sendAsynchronousRequest:queue:completionHandler:
要回答您的特定问题,在我看来response
可能会泄漏:我不知道GCD线程上是否存在隐式自动释放池。
现在做一些研究:GCD线程有自己的自动释放池,但是您不知道什么时候它们会被耗尽。您可能想用明确的自动释放池将前两个语句括起来。
另请参阅Do you need to create an NSAutoreleasePool within a block in GCD?