Summary of iOS-OC timers (NSTimer, performSelector, GCD, dispatch_source_t, CADisplayLink)

foreword

 The need for delayed execution is very common in iOS. For example, when we pop up a closeable advertisement on the home page, we need to display the pop-up advertisement only after the image is loaded or the UI is loaded.

 Here I summarize some methods of delayed execution commonly used in iOS.

NSTimer

 You should think of the timer method first, and we often use it, such as setting a 60s countdown when sending a verification code. PS: NSTimer has 8 creation methods, I have sorted it out before, please refer to " iOS-NSTimer's past and present life (the difference between different creation methods of NSTimer) ".

 I provide a method here as an example:

_myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myTimer) userInfo:nil repeats:YES];

Cancel timer method

[_myTimer invalidate];

performSelector

 performSelector: withObject: is a method invocation method in iOS, which can pass any message to an object without declaring these methods at compile time. So this is also an application of runtime.

 performSelector has no parameters and has parameter passing methods. Here I will give an example in the form of one parameter:

[self performSelector:@selector(loginWasSuccessful:) withObject:@"OneParameter"];
response function
- (void)loginWasSuccessful:(NSString *)parameter{
    NSLog(@"parameter: %@", parameter);
 }

Cancellation method

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(loginWasSuccessful:) object:nil];

Note: The function name must be consistent, otherwise the cancellation will fail.

GCD

GCD is very simple to use in the project, and I believe you use it a lot. GCD has two Dispatch Queues during execution. One is Serial Dispatch Queue, which is to wait for the end of event processing currently being executed. One is the Concurrent Dispatch Queue concurrent scheduling queue, which does not wait for the end of the currently executing event processing.

Example of use:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self.chatInputTool showInputView];//Pop up the comment box
 });

 dispatch_after does not provide a cancel method.

dispatch_source_t

 The default is repeated execution. We can cancel it through dispatch_source_cancel in the event of destruction to achieve the purpose of executing only once.

@property (strong,nonatomic)dispatch_source_t sourceTimer;
//dispatch_source_t
 - (void)createDispatch_source_t{
 
 //create global queue
 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
 
 //Create a timer using the global queue
 _sourceTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
 
 // timer delay time
 NSTimeInterval delayTime = 1.0f;
 
 // timer interval
 NSTimeInterval timeInterval = 1.0f;
 
 //set start time
 dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
 
 //set timer
 dispatch_source_set_timer(_sourceTimer,startDelayTime,timeInterval*NSEC_PER_SEC,0.1*NSEC_PER_SEC);
 
 // execute the event
 dispatch_source_set_event_handler(_sourceTimer,^{
 
    //destroy the timer
    //dispatch_source_cancel(_myTimer);
 });
 
 //start the timer
 dispatch_resume(_sourceTimer);
 }

CADisplayLink

CADisplayLink is also a timer that refreshes the screen every few millimeters. CADisplayLink is a method that allows us to draw content to the screen at the same frequency as the screen refresh rate. We create a CADisplayLink in the project and add it to RunLoop, and provide it with a target and selector.
 PS: " iOS [QuartzCore Framework] CADisplayLink "

Example of use:

@property (strong,nonatomic)CADisplayLink *displaylinkTimer;
_displaylinkTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
 [_displaylinkTimer addToRunLoop: [NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
 
 - (void)handleDisplayLink:(CADisplayLink *)displaylinkTimer{
 NSLog(@"%s-----%ld",__func__,displaylinkTimer.preferredFramesPerSecond);
 }
destroy timer
[_displaylinkTimer invalidate];
 _displaylinkTimer = nil;

Description: When the CADisplayLink object is added to the runloop, the selector can be called periodically, similar to the repeated NSTimer being started; when the invalidate operation is performed, the CADisplayLink object will be removed from the runloop, and the selector call will stop immediately. Similar to the invalidate method of NSTimer.

concluding remarks

 Welcome everyone to add!

Welcome everyone to join the mobile development technology exchange group, where everyone can discuss and learn together. There are big guys and little rookies here. If you have nothing to do, you can still fight and pretend to be forceful. If you need to change jobs, you can also recommend each other. I look forward to your participation. !giggle




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325589996&siteId=291194637