ios - dispatch_async 处理事件

标签 ios objective-c nsthread dispatch

我知道 dispatch_async 可以处理线程。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
    // handle things that takes a long time
    dispatch_async(dispatch_get_main_queue(), ^{  
        // update UI 
    });  
}); 

但是我怎样才能取消线程呢?

例如:

我有两个 View Controller - AViewController 和 BViewController,A-> 显示 B,以及一个关闭 B 的按钮。

我将在 BViewController 中执行 myMethod,我想在执行 myMethod 时关闭 B,所以我使用 dispatch_async,它确实从 B 到 A。但是在回到 AViewController 之后,音频出现了。

如何在关闭方法 exec 后立即停止 myMethod

- (void)myMethod {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
        // handles thing A
        // play a audio
        dispatch_async(dispatch_get_main_queue(), ^{  
            // update UI 
        });  
    }); 
}

最佳答案

为此您需要的不是 GCD 和 dispatch_async,而是 NSOperation。它是 GCD 的高级包装器,允许您引用异步操作、检查它们的状态、取消它们等。

我建议使用一个非常方便的名为 NSBlockOperation 的子类。你应该在你的类中保留对你的操作的引用,如果你需要取消它,只需调用 [self.myOperation cancel]

关于ios - dispatch_async 处理事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32431018/

相关文章:

ios - 如何将数据从 AppDelegate 传递到 ViewController?

ios - 为什么 AFNetworking 在第一次请求时挂起?

iphone - 非常简单的自定义 UIView,drawRect 没有被调用

ios - 在调用服务器获取数据期间无法看到 UIActivityIndi​​catorView

ios - NSThread sleepfortimeinterval 阻塞主线程

ios - 我可以让 UITextField 不可见吗?

ios - 使用 AVAudioTime 安排将来播放的音频文件

ios - ios 8.3 显示 alertview 时键盘会自动出现

iphone - 如何删除警告 "Frame for Button will be different at run time."

ios - dispatch_queue_t 是串行队列那么为什么它甚至存在于多任务概念中?