gpt4 book ai didi

objective-c - GCD dispatch_async 和 NSURLConnection

转载 作者:可可西里 更新时间:2023-11-01 04:42:33 26 4
gpt4 key购买 nike

我想要一种快速简便的方法来从 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 同步方法会导致内存泄漏。这是真的吗?

那里发布的代码是否有任何问题?将数据分配给 block 内的 self.data 有什么问题吗?

最佳答案

如果您的目标是 ios5 及更高版本,则有 NSURLConnection 的 sendAsynchronousRequest:queue:completionHandler:

为了回答您的具体问题,在我看来 response 可能会泄漏:我不知道 GCD 线程上是否存在隐式自动释放池。

现在做了一些研究:GCD 线程有它们自己的自动释放池,但你不知道它们什么时候会被耗尽。您可能希望用显式自动释放池将前两个语句括起来。

另见 Do you need to create an NSAutoreleasePool within a block in GCD?

关于objective-c - GCD dispatch_async 和 NSURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9410536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com