延迟执行代码
在Core Foundation中,我们可以performSelector:withObject:afterDelay:来延迟调用方法,GCD中如何实现呢?
使用dispatch_after,dispatch_after_f
来看个例子
double delayInSeconds = 2.0;
dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(delayInNanoSeconds, concurrentQueue, ^(void){
/* Perform your operations here */
});
第一个参数delayInNanoSeconds, 他是一个绝对时间absolute time,可以由dispatch_time获得,DISPATCH_TIME_NOW 代表当前时间now,结果返回的就是2秒后的时间。
同理,3秒钟的时间这样获得
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, 3.0f * NSEC_PER_SEC);
半秒后的时间这样获得
dispatch_time_t delay =dispatch_time(DISPATCH_TIME_NOW, (1.0 / 2.0f) * NSEC_PER_SEC);
再来看看dispatch_after_f如何使用
void processSomething(void *paramContext){
/* Do your processing here */
NSLog(@"Processing...");
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
double delayInSeconds = 2.0;
dispatch_time_t delayInNanoSeconds =dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_queue_t concurrentQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after_f(delayInNanoSeconds, concurrentQueue,NULL, processSomething);
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor
= [UIColor whiteColor]; [self.window makeKeyAndVisible];
return
YES;
}
第三个参数NULL是传递给processSomething的内存地址