"iOS Development Daily Small notes (ix)" Using Runloop in sub-threads, correct operation of Nstimer timing note three alternative methods

Source: Internet
Author: User

This article is a piece of my "iOS development Daily Small Notes" series, which is recorded in the development work today, can be explained with a short article or a small demo demo small tips. They may give the user experience, the code efficiency to get some improvement, or have not been in touch with the technology, very happy to learn, put here to be a little bit. In fact, 90% of the role is to help themselves review, memory, review.

Always wanted to write an article about Runloop study, there is no good example. My own online App store's little game "Run Beloveds" (https://itunes.apple.com/us/app/pao-ku-hao-ji-you/id914554369?mt=8) There is a good example of practical use. There is a timekeeping function in the game. In version 1.0, a simple invocation in the main thread was used:

1 + (Nstimer *) Scheduledtimerwithtimeinterval: (nstimeinterval) ti target: (ID) atarget selector: (SEL ) Aselector UserInfo: (ID) UserInfo repeats: (BOOL) Yesorno;

The method. However, when the repeat operation occurs every 0.01 seconds, Nstimer is not allowed, serious lag, and changed to 0.1 seconds repeat operation, this lag is better.

The cause of the error is that when I use the "Scheduledtimerwithtimeinterval" method, the Nstimer instance is added to the current runloop, and the pattern is nsdefaultrunloopmode. While "Current Runloop" is the main runloop of the application, this main runloop is responsible for all the main thread events, including the various events of the UI interface. When a complex operation is performed in the main thread, or when the UI interface is being manipulated, the Nstimer is "blocked" in the synchronous delivery in main runloop, and the pattern may change. As a result, delays in nstimer timings can occur.

The method of solving this kind of error is to do the Nstimer operation in the sub-thread, then modify the UI interface to display the operation result in the main thread, the other is still do nstimer operation in the main thread, but add Nstimer instance to the specific mode (mode) of main runloop. Avoid being disturbed by complex operation operations or UI refresh.

Method One:

At the beginning of the timekeeping place:

1 if (self.timer) {2        [Self.timer invalidate]; 3         Self.timer = Nil; 4     }5     self.timer = [Nstimer timerwithtimeinterval:0.01  target:self Selector: @selector (addtime) Userinfo:nil Repeats:yes]; 6     [[Nsrunloop Currentrunloop] AddTimer:self.timer formode:nsrunloopcommonmodes];

[Nsrunloop currentrunloop] Gets the "main Runloop", using Nsrunloopcommonmodes mode, add Nstimer to it.

(Borrowed from the blog: http://www.mgenware.com/blog/?p=459)

Method Two:

Threading: (Runloop with sub-threads)

1 Object : nil]; 2     [Thread start];
1 -(void) newthread2{3    @autoreleasepool4      {5         [nstimer scheduledtimerwithtimeinterval:2.0  target:self Selector: @selector (addtime) Userinfo:nil Repeats:yes]; 6         [[Nsrunloop Currentrunloop] run]; 7     }8 }

The Nstimer is added to the thread's Runloop by default in the child thread, starting the child thread.

Method Three:

Using GCD is also a multithreaded approach:

Declaring global member variables

1 dispatch_source_t _timers;
1uint64_t interval =0.01*nsec_per_sec;2dispatch_queue_t queue = Dispatch_queue_create ("My Queue",0);3_timers = Dispatch_source_create (Dispatch_source_type_timer,0,0, queue);4Dispatch_source_set_timer (_timers, Dispatch_time (Dispatch_time_now,0), Interval,0);5__weak Viewcontroller *blockself =Self ;6Dispatch_source_set_event_handler (_timers, ^()7     {8NSLog (@"Timer%@", [Nsthread CurrentThread]);9 [Blockself addtime];Ten     }); OneDispatch_resume (_timers);

Then modify the UI interface in the main thread:

1 dispatch_async (Dispatch_get_main_queue (), ^{2         self.label.text = [NSString stringWithFormat:@ "%.2f", self.timecount/]; 3     });

The game source code is visible:https://github.com/pigpigdaddy/BothLive

Summarize:

Runloop is a seemingly mysterious thing, in fact, it is not mysterious. Each thread has a runloop that actually exists. For example, our main thread, in the uiapplication of the main function:

1 class]))

The system then implicitly launches the main runloop of the main thread. Runloop as the name implies is a "loop", he kept running, from the beginning of the program to the program exit. It is because of this "cycle" in the continuous monitoring of various events, the program is able to detect the user's various touch interactions, the data returned by the network will be detected, the timer will trigger the operation at a predetermined time ...

Runloop only accepts two types of tasks: input source and timing source. This article is about timing sources. By default, the runloop of a child thread does not include our own source, so when we use our own timers in a child thread, we need to add ourselves to the Runloop and start the runloop of the child thread to run the timer correctly.

Reference article:

http://www.mgenware.com/blog/?p=459

http://blog.csdn.net/wzzvictory/article/details/9237973

Http://www.dahuangphone.com/dv_rss.asp?s=xhtml&boardid=8&id=93&page=5

http://www.hrchen.com/2013/07/tricky-runloop-on-ios/

Http://www.cnblogs.com/vicstudio/p/3281682.html

"iOS Development Daily Small notes (ix)" Using Runloop in sub-threads, correct operation of Nstimer timing note three alternative methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.