[Switch] several timer types in iOS, ios Timer

Source: Internet
Author: User

[Switch] several timer types in iOS, ios Timer

This article is reprinted content, the original address: http://www.cocoachina.com/ios/20150519/11857.html? Utm_source = tuicool

The knowledge points here are common in our daily development. For example, I wrote two essays:

Use of NSTimer: 178 to achieve the effect of Flying Snow in the sky

CADisplayLink usage: 156 difference between UIImageView and CADisplayLink for Tom Cat animation effect (extended knowledge: Grouping (yellow folder) and folder reference (blue folder)

 

----------------------------- Not very gorgeous split line, the following is the reprinted content -------------------------------

In the process of software development, we often need to execute a method after a certain time, or always execute a method according to a certain cycle. At this time, we need to use a timer.

However, there are many methods in iOS to complete the above tasks. How many methods are there? After reading the information, there are three methods: NSTimer, CADisplayLink, and GCD. Next I will introduce their usage one by one.

I. NSTimer

1. Creation Method

1 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action:) userInfo:nil repeats:NO];
  • TimerInterval: The waiting time before execution. For example, if it is set to 1.0, it indicates the method to be executed in 1 second.

  • Target: The object of the method to be executed.

  • Selector: Method to be executed

  • Repeats: Whether loop is required

2. Release Method

1 [timer invalidate];
  • Note:

After the creation method is called, the counter of the target object is incremented by 1 until the execution is completed, and 1 is automatically subtracted. If it is executed cyclically, you must manually disable it; otherwise, you can skip the release method.

3. Features

  • Latency

Whether it is a one-time or periodic timer's actual trigger event time, it will be related to the added RunLoop and RunLoop Mode. If this RunLoop is executing a continuous operation, timer will be delayed. In this case, if the delay exceeds a cycle, the timer runs immediately after the delay ends and continues the execution according to the specified cycle.

  • Runloop must be added.

Using the above creation method, timer is automatically added to NSDefaultRunLoopMode of MainRunloop. If you use the following method to create a timer, you must manually add the Runloop:

1 NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];2 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

 

Ii. CADisplayLink

1. Creation Method

1 self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];    2 [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

2. Stop Method

1 [self. displayLink invalidate]; 2 self. displayLink = nil; 3 4/** when the CADisplayLink object is added to the runloop, the selector can be periodically called, similar to the repeated NSTimer being started; when the invalidate operation is executed, the CADisplayLink object is removed from runloop, And the selector call is stopped immediately, similar to the invalidate method of NSTimer. **/

3. Features

  • Call when screen refreshing

    CADisplayLink is a Timer class that allows us to draw specific content to the screen at a frequency that synchronizes with the screen update rate. After CADisplayLink is registered to runloop in a specific mode, runloop sends a specified selector message to the target specified by CADisplayLink whenever the screen displays the content refreshed, the selector corresponding to the CADisplayLink class will be called once. Therefore, the screen update rate for iOS devices is usually 60 times per second.

  • Latency

    • The screen refresh frequency of iOS devices is fixed. CADisplayLink is normally called at the end of each refresh, with a high accuracy. However, if the called method is time-consuming and exceeds the screen refresh cycle, several callback call opportunities will be skipped.

    • If the CPU usage is too busy and the screen refreshing rate cannot be guaranteed for 60 times/Second, several chances of calling the callback method will be skipped. The number of skipping times depends on the CPU usage.

  • Use Cases

    It can be seen from the principle that CADisplayLink is suitable for non-stop screen repainting. For example, you need to continuously obtain the next frame during video playback for interface rendering.

4. Important attributes

  • FrameInterval

    Specifies the number of frames at which the selector method is called. The default value is 1, that is, each frame is called.

  • Duration

    The CFTimeInterval value of readOnly, indicating the interval between two screen refreshes. Note that this attribute is assigned a value only after the target selector is called for the first time. The call interval Calculation Method of selector is as follows: Call interval = duration × frameInterval.

 

Iii. GCD Mode

  • Run Once

  • 1 double delayInSeconds = 2.0; 2 dispatch_time_t popTime = dispatch_time (DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 3 dispatch_after (popTime, interval (), ^) {4 // execution event 5 });
  • Repeated execution

  • 1 NSTimeInterval period = 1.0; // set the interval of 2 dispatch_queue_t queue = queue (queue, 0); 3 dispatch_source_t _ timer = dispatch_source_create (queue, 0, 0, queue ); 4 dispatch_source_set_timer (_ timer, dispatch_walltime (NULL, 0), period * NSEC_PER_SEC, 0); // execute 5 dispatch_source_set_event_handler (_ timer, ^ {6 // execute event 7}); 8 dispatch_resume (_ timer );

 

Related Article

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.