6.8 Performing Tasks After a Delay with GCD

本文介绍如何使用GCD的dispatch_after及dispatch_after_f实现指定时间后的代码执行,包括具体实现方式和示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


延迟执行代码

在Core Foundation中,我们可以performSelector:withObject:afterDelay:来延迟调用方法,GCD中如何实现呢?

使用dispatch_afterdispatch_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的内存地址








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值