gpt4 book ai didi

iphone - 在 Objective C 中使用 block 编程进行内存管理

转载 作者:可可西里 更新时间:2023-11-01 04:44:49 25 4
gpt4 key购买 nike

我正在阅读以下有关调度队列中完成 block 的 Apple 文档,但我无法理解其中的一部分。该文件提到“为了防止过早释放队列,最初保留该队列并在分派(dispatch)完成 block 后释放它是至关重要的。”这与我在 Block Programming Guide 中提到的 block 在其闭包中保留所有变量的理解相矛盾。

我在这里错过了什么?文档中的片段粘贴在下面:

A completion block is just another piece of code that you dispatch to a queue at the end of your original task. The calling code typically provides the completion block as a parameter when it starts the task. All the task code has to do is submit the specified block or function to the specified queue when it finishes its work.

Listing 3-4 shows an averaging function implemented using blocks. The last two parameters to the averaging function allow the caller to specify a queue and block to use when reporting the results. After the averaging function computes its value, it passes the results to the specified block and dispatches it to the queue. To prevent the queue from being released prematurely, it is critical to retain that queue initially and release it once the completion block has been dispatched.Listing 3-4 Executing a completion callback after a task

void average_async(int *data, size_t len, dispatch_queue_t queue, void (^block)(int))
{
// Retain the queue provided by the user to make
// sure it does not disappear before the completion
// block can be called.
dispatch_retain(queue);

// Do the work on the default concurrent queue and then
// call the user-provided block with the results.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
int avg = average(data, len);
dispatch_async(queue, ^{ block(avg);});

// Release the user-provided queue when done
dispatch_release(queue);
});
}

最佳答案

This contradicts my understanding that the block retains all the variables in its closure

这不是矛盾,而是误解。 block 保留它引用的所有objective-c 对象。其他对象类型使用它们自己的保留函数而不是标准函数。因此,运行时不可能知道如何保留 block 可能包含的每个变量。这就是为什么需要手动保留和释放队列的原因。

关于iphone - 在 Objective C 中使用 block 编程进行内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6064643/

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