此行在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);
}