在IOS中如何通过gcd延迟调用方法?

时间:2015-09-23 13:03:36

标签: ios objective-c

有没有为什么在调度后用2秒调用方法,就像performSelector:withObject:afterDelay:?

3 个答案:

答案 0 :(得分:8)

是的,你可以,

Swift 3,Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    <# YOUR CODE HERE #>
}

Swift 2

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
        <# YOUR CODE HERE #>
}

目标C

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        <# YOUR CODE HERE #>
    });

答案 1 :(得分:2)

是的,我们可以使用以下代码添加延迟来执行GCD

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
 // Do you work over here
});

希望这会对你有所帮助。

答案 2 :(得分:1)

dispatch_time_t deferTime = 2.0f;
dispatch_after(deferTime, dispatch_get_main_queue(), ^{
//call you method here
});