Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

ios5 - Difference in scheduling NSTimer in main thread and background thread?

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.

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?

question from:https://stackoverflow.com/questions/12323531/difference-in-scheduling-nstimer-in-main-thread-and-background-thread

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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.

  2. 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;

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...