scheduledTimerWithTimeInterval

scheduledTimerWithTimeInterval

本文介绍了在主线程和后台线程中调度 NSTimer 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在主线程上调用 scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: 并将时间间隔设置为 5 秒时,计时器下方的代码将被执行,并在 5 秒后调用计时器选择器.

When I call scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: on the main thread and set time interval to 5 seconds code below timer gets executed, and after 5 seconds timer selector is called.

但如果我在某个后台线程中尝试相同的操作,scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: 下面的代码将不会被执行,它会等待计时器触发然后被执行.当然,为了在后台线程中运行定时器,我首先得到了一个NSRunLoop的实例并运行它.

But if I try same in some background thread, the code below scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: will not be executed, it will wait for the timer to fire and then gets executed. Of course, in order to run the timer in the background thread, I first got an instance of NSRunLoop and run it.

有没有办法在后台线程中设置定时器并使其非阻塞,所以它立即执行后的代码?

Is there a way to set the timer in the background thread and make it non-blocking, so code after it gets executed immediately?

推荐答案

NSTimer 需要一个活动的运行循环,在主线程中初始化时它会自动使用主运行循环.如果您需要创建一个后台计时器,您需要将其附加到线程的运行循环并调用 run() 以使其处于活动状态.

NSTimer requires an active run loop, when initialized in Main Thread it automatically uses the main run loop. If you need to make a background timer you need attach it to the thread’s run loop and invoke run() to make it active.

  1. NSTimer 需要一个实时的 NSRunLoop 来执行它的事件.在主线程中,NSRunLoop 始终处于活动状态,并且在应用程序终止之前永远不会停止,但在其他线程中,您必须调用 run() 来激活 NSRunLoop.

  1. NSTimer needs one live NSRunLoop to execute it’s events. In main thread, the NSRunLoop is always live and will never stop until the app is terminated, but in other threads, you must invoke run() to active the NSRunLoop.

NSTimer 必须调用 invalidate() 来释放当前计时器,否则,计时器将保留当前目标实例的强引用,并且它将保留在内存中,直到调用 invalidate() 或应用程序终止;

NSTimer must invoke invalidate() to release the current timer, otherwise, the timer will retain a strong reference of the current instance of target, and it will remain in memory until invalidate() invoked or app terminated;

NSTimer 必须在同一个线程中创建和失效,而且很多时候,我们可能会忘记这一点.

NSTimer must created and invalidated in the same thread, and a lot of times, we may forget that.

看看这个例子,它可能会有所帮助>> http://www.acttos.org/2016/08/NSTimer-and-GCD-Timer-in-iOS/和文档:https://developer.apple.com/documentation/foundation/nstimer

Take a look at this example , it may be helpful >> http://www.acttos.org/2016/08/NSTimer-and-GCD-Timer-in-iOS/ and the documentation : https://developer.apple.com/documentation/foundation/nstimer

这篇关于在主线程和后台线程中调度 NSTimer 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:05