定时任务

方法1:performSelector

// 1.5s后自动调用self的test1方法
[self performSelector:@selector(test1) withObject:nil afterDelay:1.5];

方法2:GCD

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

     // 1.5s后自动执行这个block里面的代码

});

 

方法3:NSTimer

// 1.5s后自动调用self的test2方法,repeats如果为YES,意味着每隔1.5s都会调用一次
[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(test2) userInfo:nil repeats:NO]; 
// 解决定时器在主线程不工作的问题
NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(test3) userInfo:nil repeats:YES];

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
// 通过invalidate方法可以停止定时器的工作,一旦定时器被停止了,就不能再次执行任务。只能再创建一个新的定时器才能执行新的任务
- (void)invalidate;
原文地址:https://www.cnblogs.com/pengyunjing/p/5690377.html