【问题标题】:Can block capture a CoreFundation object?可以阻止捕获 CoreFundation 对象吗?
【发布时间】:2014-11-23 07:36:16
【问题描述】:

Apple's doc 中,当我想捕获 CoreFoundation 对象时,我找不到我能做什么。

但在 Apple 的 Concurrency Programming Guide 中。当调度对象不支持ARC时,示例代码似乎使用了一些代码,就像这样:

   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);

       });
   }

我是否需要像之前的DispatchObject 一样使用CFObject。但是如果我需要多次调用该块呢?

也许我可以使用__attribute__((NSObject)),但我不知道会发生什么!

Apple 对此有什么说法吗?

【问题讨论】:

    标签: ios objective-c automatic-ref-counting objective-c-blocks core-foundation


    【解决方案1】:

    首先,dispatch_queue_t 不是 Core Foundation 对象。

    Dispatch 对象被编译器视为 Objective-C 对象(用于 ARC 和块目的)if your deployment target is iOS 6+ / OS X 10.8+

    【讨论】:

    • 我并不是说 dispatch_queue 是一个核心基金对象。我只是认为它必须像 iOS6 之前的 Core Fundation 对象一样管理它的内存。所以我想知道当一个核心基金对象被一个块捕获时如何管理它,因为我在苹果的文档中看不到任何东西。
    【解决方案2】:

    我没有在 Apple 明确看到任何东西,但我确实看到了一些 mentions in the llvm.org documentation,我发现在 in this cocoa-dev mailing list thread 上进行了详细说明。

    看起来你应该可以使用__attribute__((NSObject)),因为它被赋予了一个隐含的“__strong”资格(来自文档)并且在实际意义上(来自邮件列表线程),当当块完成时,该块排队并释放。

    【讨论】:

    • 我也有关于如何使用 __attribute__((NSObject)) 的帖子a question)。使用它时似乎事情变得很奇怪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 2023-03-19
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多