iOS / Objective-C等同于Android的AsyncTask

我熟悉在Android中使用AsyncTask:创建子类,在子类的实例上调用execute,onPostExecute在UI线程或主线程上调用。在iOS中相当于什么?
原问题:

Grand Central Dispatch(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对象,因此您不必担心调用这些函数。参考关于GCD和ARC的rob mayoff’s great answer,您可以看到文档描述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有一个分组接口支持同步多个异步块,如果一个任务不能继续,直到多个异步活动完成。 JörnEyrich和ɲeuroburɳ提供了对这个主题here的慷慨解释。如果你需要这个功能,我强烈建议花几分钟来仔细阅读他们的答案,并了解他们之间的差异。

如果你这么倾向,documentation有关于这个话题的丰富的信息。

http://stackoverflow.com/questions/11728098/ios-objective-c-equivalent-of-androids-asynctask

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:iOS / Objective-C等同于Android的AsyncTask