scheduledTimerWithTimeInterval timerWithTimerInterval区别。

有三种方法来创建一个定时器

1.使用scheduledTimerWithTimeInterval

类方法创建计时器和进度上当前运行循环在默认模式(NSDefaultRunLoopMode)

2.使用timerWithTimerInterval

类方法创建计时器对象没有调度运行循环(RunLoop)

在创建它,必须手动添加计时器运行循环,通过调用adddTimer:forMode:方法相应的NSRunLoop对象

3.使用initWithFireDate

在创建它,必须手动添加计时器运行循环,通过使用addTimer:forMode:方法相应的NSRunLoop对象

 

1.

复制代码
- (void)execute {
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}
复制代码

2.

- (void)execute {
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
    //为什么在主线程不需要这句run,那是因为主线程有RunLoop而且已经启动
    [[NSRunLoop currentRunLoop] run];
}



给人感觉还是使用timerWithTimerInterval这种方式好些,可控性强一些,而且可以不用因为主线程阻塞(如视频推拉流)而造成timer的事件卡顿.


例如这样一个跑马灯的效果:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            self.LampTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(lampsStart:) userInfo:nil repeats:YES];
            self.LampTimer = [NSTimer timerWithTimeInterval:0.618 target:self selector:@selector(lampsStart:) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.LampTimer forMode:NSRunLoopCommonModes];
            [self.LampTimer fire];
            [[NSRunLoop currentRunLoop] run];
        });



更多问题,欢迎加群讨论:qq群 :565191947
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值