iOS 定时器延迟执行

2020-05-07  本文已影响0人  清风_____

1、NSRunLoop

[self performSelector:@selector(laterExecute) withObject:nil afterDelay:5.0f];

2、定时器

//不带参数
[NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(laterExecute) userInfo:nil repeats:NO];

-(void)laterExecute
{
    NSLog(@"执行了");
}


//带参数
[NSTimer scheduledTimerWithTimeInterval:0.5 
                       target:self 
                       selector:@selector(sendBroadcast:) 
                       userInfo:@"hello I'm the info to send" 
                       repeats:NO];
// sendBroadcast的定义形式应该是
-(void)sendBroadcast: (NSTimer *)timer { 

   NSString *msg = (NSString *)[timer userInfo]; // [msg isEqualToString @"hello I'm the info to send"] == YES
}

3、GCD

    double delayInSeconds = 5.0;
    __block ViewController *selfBlcok = self;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
        [selfBlcok laterExecute];
    }); 

https://www.jianshu.com/p/2d57c72016c6

上一篇 下一篇

猜你喜欢

热点阅读