Objective-C与块的延迟行为

我知道在Objective-C中有几种延迟操作的方法,例如:

performSelector:withObject:afterDelay: 

或使用NSTimer

但是有一个叫块的东西,你可以这样做:

 [UIView animateWithDuration:1.50 delay:0 options:(UIViewAnimationOptionCurveEaseOut|UIViewAnimationOptionBeginFromCurrentState) animations:^{ }completion:^(BOOL finished){ }]; 

不幸的是,这种方法只适用于animation的东西。

我怎样才能创build一个块的延迟在一个方法,所以我不必使用所有这些@select器,而不需要创build一个新的单独的方法 ? 谢谢!

使用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]; }); 

扩大接受的答案,我创build了一个助手function,任何人不关心记忆语法每次他们想这样做:)我只是有一个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(); } }); } 

下面是如何在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) } 

它包含在我的回购标准function: https : //github.com/goktugyil/EZSwiftExtensions