Метод отложенного выполнения iOS

Перейдите непосредственно к коду:

Между этими четырьмя методами есть некоторые основные различия, и я расскажу вам о них позже.

// 第一种不带参数
[self performSelector:@selector(yourFunction) withObject:nil afterDelay:1.0f];
// 带参数
[self performSelector:@selector(delayDo:) withObject:@"abc" afterDelay:1.0f];


// 第二种在主线程延迟
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)1*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        //此处写执行代码
    });
// 第二种在子线程延迟
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      //此处写执行代码
      });

// 第三种会延迟当前线程状态,最好不要在主线程设置
[NSThread sleepForTimeInterval:1];

// 第四种
NSTimer * timer;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayDo:) userInfo:@"abc" repeats:YES];
    NSTimer *timer1;
    timer1 = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(aaa) userInfo:@"aaa" repeats:YES];
    [timer setFireDate:[NSDate date]];
    [timer fire];
    [timer invalidate];

Guess you like

Origin blog.csdn.net/JustinZYP/article/details/124672665
ios