ios 带有块的 Objective-C 延迟动作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15413014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C delay action with blocks
提问by Sergey Grischyov
I know that there are several ways of delaying an action in Objective-C like:
我知道在 Objective-C 中有几种延迟操作的方法,例如:
performSelector:withObject:afterDelay:
or using NSTimer
.
或使用NSTimer
.
But there is such a fancy thing called blocks where you can do something like this:
但是有一种叫做块的奇特东西,您可以在其中执行以下操作:
[UIView animateWithDuration:1.50 delay:0 options:(UIViewAnimationOptionCurveEaseOut|UIViewAnimationOptionBeginFromCurrentState) animations:^{
}completion:^(BOOL finished){
}];
Unfortunately, this method applies only to animating things.
不幸的是,这种方法仅适用于动画事物。
How can I create a delay with a block in one methodso I don't have to use all those @selectors
and without the need to create a new separate method? Thanks!
如何在一种方法中使用块创建延迟,以便我不必使用所有这些@selectors
并且无需创建新的单独方法?谢谢!
回答by Martin Ullrich
use dispatch_after:
使用 dispatch_after:
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//code to be executed on the main queue after delay
[self doSometingWithObject:obj1 andAnotherObject:obj2];
});
回答by rckehoe
Expanding on the accepted answer, I created a Helper function for anyone who doesn't care to memorize the syntax each time they want to do this :) I simply have a Utils class with this:
扩展已接受的答案,我为任何不想记住语法的人创建了一个 Helper 函数,他们每次想要这样做:) 我只是有一个 Utils 类:
Usage:
用法:
[Utils delayCallback:^{
//--- code here
} forTotalSeconds:0.3];
Helper method:
辅助方法:
+ (void) delayCallback: (void(^)(void))callback forTotalSeconds: (double)delayInSeconds{
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
if(callback){
callback();
}
});
}
回答by Esqarrouth
Here is how you can trigger a block after a delay in Swift:
以下是在 Swift 中延迟后触发块的方法:
runThisAfterDelay(seconds: 4) { () -> () in
print("Prints this 4 seconds later in main queue")
// Or just call animatedMyObject() right here
}
/// EZSwiftExtensions
func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), after)
}
Its included as a standard function in my repo: https://github.com/goktugyil/EZSwiftExtensions
它作为标准函数包含在我的 repo 中:https: //github.com/goktugyil/EZSwiftExtensions