我熟悉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
});
如果要在后台执行任务并在后台任务完成后更新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
});
});
创建队列时,还可以使用该dispatch_get_global_queue()
函数获取具有特定优先级的全局调度队列(例如DISPATCH_QUEUE_PRIORITY_HIGH
)。这些队列是可普遍访问的,并且在您要将多个任务分配给同一线程/队列时很有用。请注意,内存完全由iOS管理。
有时有关于内存管理和调度队列,因为他们有自己的一些困惑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.
我还要补充一点,如果任务在多个异步活动完成之前无法继续执行,那么GCD的分组接口支持同步多个异步块。乔恩Eyrich和ɲeuroburɳ提供这个话题的一个慷慨的解释在这里。如果您需要此功能,我强烈建议您花几分钟时间仔细阅读它们的两个答案并了解它们之间的区别。
如果您愿意的话,文档中包含有关该主题的大量信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句