前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >NSTimer scheduledTimerWithTimeInterval与timerWithTimeInterval、initWithFireDate的区别

NSTimer scheduledTimerWithTimeInterval与timerWithTimeInterval、initWithFireDate的区别

作者头像
全栈程序员站长
发布2022-09-07 10:31:15
2530
发布2022-09-07 10:31:15
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

英文原文是这样的:

A timer object can be registered in only one run loop at a time, although it can be added to multiple run loop modes within that run loop. There are three ways to create a timer:

Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A non-repeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method. Calling this method requests the removal of the timer from the current run loop; as a result, you should always call the invalidate method from the same thread on which the timer was installed. Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes the timer (and the strong reference it had to the timer), either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.

翻译过来大体是这样的:

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

1.使用scheduledTimerWithTimeInterval

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

2.使用timerWithTimerInterval

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

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

3.使用initWithFireDate

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

1.

代码语言:javascript
复制
- (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.

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

这两个代码效果是一样的,scheduledTimerWithTimeInterval相当于timerWithTimeInterval的两句。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/154696.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档