我有一个异步任务,如下所示:
dispatch_async(dispatch_get_main_queue(), ^{
myAsyncMethodsHere;
});
有没有一种方法可以在后台任务完成时得到通知?
或者在完成后调用一个方法?
我已经阅读了文档并研究了dispatch_after,但似乎它更多地是设计用来在一定时间后调度方法。
感谢帮助。
我有一个异步任务,如下所示:
dispatch_async(dispatch_get_main_queue(), ^{
myAsyncMethodsHere;
});
有没有一种方法可以在后台任务完成时得到通知?
或者在完成后调用一个方法?
我已经阅读了文档并研究了dispatch_after,但似乎它更多地是设计用来在一定时间后调度方法。
感谢帮助。
从文档中得知:
完成回调可以通过嵌套调用dispatch_async()函数实现。重要的是要在第一次调用dispatch_async()之前保留目标队列,并在完成回调结束时释放该队列,以确保目标队列在完成回调等待期间不会被释放。例如:
void
async_read(object_t obj,
void *where, size_t bytes,
dispatch_queue_t destination_queue,
void (^reply_block)(ssize_t r, int err))
{
// There are better ways of doing async I/O.
// This is just an example of nested blocks.
dispatch_retain(destination_queue);
dispatch_async(obj->queue, ^{
ssize_t r = read(obj->fd, where, bytes);
int err = errno;
dispatch_async(destination_queue, ^{
reply_block(r, err);
});
dispatch_release(destination_queue);
});
}
dispatch_release
只会释放您对其的句柄。块将始终拥有一个句柄。一旦块消失,队列也将消失。 - Ben Scheirman