I know that there are several ways of delaying an action in Objective-C like:

performSelector:withObject:afterDelay:

or using 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 method so I don't have to use all those @selectors and without the need to create a new separate method? Thanks!

推荐答案

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

Objective-c相关问答推荐

Apple Silicon 上的 dispatch_time 计算失败

如何使 UIView 动画序列重复和自动反转

iphone 的 UIPopoverController 不工作?

我应该打电话给 [super awakeFromNib] 吗?

NSTimeZone:localTimeZone 和 systemTimeZone 有什么区别?

如何将 NSDate 转换为今天、昨天、一周前、一个月前、一年前等相对格式?

如何在目标 C 中创建单例类

只有 ONE VIEW 横向模式

当单元格全屏时,为什么 UICollectionView 会记录错误?

Objective-C 中的 const 与静态 NSStrings

当服务器上的图像文件更改时,我的应用程序中的 SDWebImage 缓存图像会发生什么情况?

如何确定 UICollectionView flowLayout 中单元格之间的间距

Cocoa 与 Cocoa Touch - 有什么区别?

Select 时 UITableViewCell 复选标记更改

iPhone 上 SQLite 的最佳 Cocoa/Objective-C 包装器库

使用 CocoaPods 时如何向 Xcode 添加自定义项目配置?

在 Objective-C 中计算两个日期之间的天数

从视图中删除所有子图层

使用 Objective-C 发布多部分/表单数据

Xcode 在调试时判断表达式