此行在 3 秒后调用选择器 secondMethod:
[self performSelector:@selector(secondMethod) withObject:nil afterDelay:3.0 ];
在您的第二次操作中使用它并获得所需的延迟。如果您有很多代码,请将其放在自己的方法中并使用performSelector:
. 它不会像sleep
编辑:如果您不想要第二种方法,您可以添加一个类别以便能够将块与 performSelector 一起使用:
@implementation NSObject (PerformBlockAfterDelay)
- (void)performBlock:(void (^)(void))block
afterDelay:(NSTimeInterval)delay
{
block = [block copy];
[self performSelector:@selector(fireBlockAfterDelay:)
withObject:block
afterDelay:delay];
}
- (void)fireBlockAfterDelay:(void (^)(void))block
{
block();
}
@end
或者甚至更清洁:
void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
dispatch_get_current_queue(), block);
}