cocoa 延时 NSTimer

本文介绍了如何使用Objective-C中的NSTimer类来实现延时功能,包括使用timer对象进行延时调用和定时器的重复使用。通过实例演示了如何设置定时器的时间间隔、目标、选择器和信息参数,以及如何终止定时器。

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

利用Timer定时器

NSTimer *connectionTimer;//timer对象
//实例化timer
self.connectionTimer=[NSTimerscheduledTimerWithTimeInterval:1.5 target:selfselector:@selector(timerFired:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop]addTimer:self.connectionTimer forMode:NSDefaultRunLoopMode];

//用timer作为延时的一种方法
do{
[[NSRunLoopcurrentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]];
}while(!done);
//timer调用函数
-(void)timerFired:(NSTimer *)timer{
done =YES;
}
//用timer作为延时的一种方法

[NSTimerscheduledTimerWithTimeInterval:0.5target:selfselector:@selector(handleTimer: )userInfo:nilrepeats:NO] ;

-(void)handleTimer:(NSTimer *)timer

~~~


[timerinvalidate];//这句代码用来终止timmer,

延时函数:
[NSThread sleepForTimeInterval:5.0];//暂停5s.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值