MRC下计时器

本文介绍了如何使用NSTimer在iOS开发中实现定时任务。包括三种不同的创建计时器的方法:直接调度、延迟启动以及确保计时器加入到NSRunLoop中运行。此外还提供了如何让计时器立即执行及停止的有效方案。

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

NSTimer,计时器,作用:每隔多少秒执行相应的方法

   
//创建方法1
   
    [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(start:) userInfo:nil repeats:YES];
    [NSTimer scheduledTimerWithTimeInterval:7.0 target:self selector:@selector(stop:) userInfo:nil repeats:YES];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(print:) userInfo:@"ASXD" repeats:YES];
   
   
//创建方法2
   
    NSDate *fiveDate = [NSDate dateWithTimeIntervalSinceNow:5];
    NSTimer *timer2 = [[NSTimer alloc] initWithFireDate:fiveDate interval:1 target:self selector:@selector(start:) userInfo:nil repeats:YES];
   
   
每个线程(thread)中都有一个事件循环(NSRunLoop),来时时判断是否执行某些事件或方法
   
加入到事件循环中,通过init方式创建的timer不能执行,需要加入到NSRunLoop
    [[NSRunLoop currentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
    [timer2 release];
   
   //立即执行第一次操作
    [timer2 fire];
    //停止计时器
    [timer2 invalidate];
   
   
//创建方法3
    NSTimer *timer3 = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(print:) userInfo:nil repeats:YES];
    //添加到主线程的事件循环中
    [[NSRunLoop mainRunLoop] addTimer:timer3 forMode:NSDefaultRunLoopMode];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值