iOS / Objective-C相当于Android的AsyncTask

星期天星期一

我熟悉AsyncTask在Android中使用的方法:创建一个子类,execute在该子类的实例上onPostExecute调用,然后在UI线程或主线程上调用。iOS中的等效功能是什么?

埃里克·米切尔

原始问题的答案:

大型中央调度(GCD)提供了一种在后台执行任务的机制,尽管它在结构上与AsyncTask不同。要异步执行某些操作,您只需要创建一个队列(如线程),然后传递一个dispatch_async()要在后台执行的块我发现它比AsyncTask整洁,因为没有涉及子类;无论您要在后台执行的代码如何,它都可以即插即用。一个例子:

dispatch_queue_t queue = dispatch_queue_create("com.yourdomain.yourappname", NULL);
dispatch_async(queue, ^{
    //code to be executed in the background
});

其他要点:

1)回调

如果要在后台执行任务并在后台任务完成后更新UI(或在另一个线程上执行某些操作),则可以简单地嵌套调度调用:

dispatch_queue_t queue = dispatch_queue_create("com.yourdomain.yourappname", NULL);
dispatch_async(queue, ^{
    //code to be executed in the background
    dispatch_async(dispatch_get_main_queue(), ^{
        //code to be executed on the main thread when background task is finished
    });
});

2)全局队列

创建队列时,还可以使用该dispatch_get_global_queue()函数获取具有特定优先级的全局调度队列(例如DISPATCH_QUEUE_PRIORITY_HIGH)。这些队列是可普遍访问的,并且在您要将多个任务分配给同一线程/队列时很有用。请注意,内存完全由iOS管理。

3)记忆

有时有关于内存管理和调度队列,因为他们有自己的一些困惑dispatch_retain/dispatch_release功能。但是,请放心,它们被ARC视为Objective-C对象,因此您不必担心调用这些函数。参考rob mayoff关于GCD和ARC的很好的答案,您可以看到文档描述了GCD队列与Objective-C对象的等效性:

* By default, libSystem objects such as GCD and XPC objects are declared as
* Objective-C types when building with an Objective-C compiler. This allows
* them to participate in ARC, in RR management by the Blocks runtime and in
* leaks checking by the static analyzer, and enables them to be added to Cocoa
* collections.
*
* NOTE: this requires explicit cancellation of dispatch sources and xpc
*       connections whose handler blocks capture the source/connection object,
*       resp. ensuring that such captures do not form retain cycles (e.g. by
*       declaring the source as __weak).
*
* To opt-out of this default behavior, add -DOS_OBJECT_USE_OBJC=0 to your
* compiler flags.
*
* This mode requires a platform with the modern Objective-C runtime, the
* Objective-C GC compiler option to be disabled, and at least a Mac OS X 10.8
* or iOS 6.0 deployment target.

4)多个任务/块

我还要补充一点,如果任务在多个异步活动完成之前无法继续执行,那么GCD的分组接口支持同步多个异步块。乔恩Eyrich和ɲeuroburɳ提供这个话题的一个慷慨的解释在这里如果您需要此功能,我强烈建议您花几分钟时间仔细阅读它们的两个答案并了解它们之间的区别。

如果您愿意的话文档中包含有关该主题的大量信息。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章