GCD定时器不起作用原因

时间:2021-11-13 19:26:56

要将timer保存起来,不然timer复制完就释放掉了

@interface ViewController ()
{
    dispatch_source_t timer;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    dispatch_queue_t quete = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 1);
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quete);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        NSLog(@"aaaaaaaaaaa");
    });
    dispatch_resume(timer);
}