我知道在Objective-C中有几种延迟动作的方法,如:
performSelector:withObject:afterDelay:
或使用NSTimer
。
但是有一种叫做积木的奇特东西,你可以做这样的事情:
[UIView animateWithDuration:1.50 delay:0 options:(UIViewAnimationOptionCurveEaseOut|UIViewAnimationOptionBeginFromCurrentState) animations:^{
}completion:^(BOOL finished){
}];
不幸的是,这种方法仅适用于动画。
如何在一个方法中使用块创建延迟,这样我就不必使用所有@selectors
并且无需创建新的单独方法?谢谢!
答案 0 :(得分:122)
使用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];
});
答案 1 :(得分:23)
扩展已接受的答案,我为那些每次不想记住语法的人创建了一个帮助函数:)我只是有一个这样的Utils类:
用法:
[Utils delayCallback:^{
//--- code here
} forTotalSeconds:0.3];
帮助方法:
+ (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();
}
});
}
答案 2 :(得分:2)
以下是在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)
}
它作为我的回购中的标准功能包含在内: https://github.com/goktugyil/EZSwiftExtensions
答案 3 :(得分:1)