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

标签 iphone multithreading ios objective-c-blocks

我正在阅读以下有关调度队列中完成 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/

相关文章:

ios - CloudKit CK引用列表

iphone - 重命名持久存储协调器 URL

ios - iOS UITableView如何在NavigationBar下使用?

c++ - C++ 11 中的锁是否保证访问数据的新鲜度?

iphone - ASIHTTPRequest调试

java - 如何在两个无限循环线程之间共享单个列表?

java - 我们是否可以说,通过同步代码块,我们使所包含的语句成为原子的?

ios - 将 Parse Push Notifications 集成到 Xcode 7 项目中 (Swift)

ios - Swift- EXC_CRASH (SIGABRT) 如何使用此堆栈跟踪查找异常

iphone - 像通知栏一样在 iPhone 中拉起 View