OC底层performSelector:@selector(test) withObject:nil afterDelay:

-(void)test{
    NSLog(@"2");
}

-(void)test2{
    NSLog(@"3");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //并发队列
    dispatch_queue_t queue = dispatch_queue_create("batac.com", DISPATCH_QUEUE_CONCURRENT);
    //异步处理任务
    dispatch_async(queue, ^{
        //异步并发队列处理任务, 会开启子线程处理任务
        NSLog(@"1");
        [self performSelector:@selector(test) withObject:nil afterDelay:.0];
        [self performSelector:@selector(test2) withObject:nil];
        NSLog(@"4");
    });
}

以上内容会打印什么?

// 1   3    4

  • 原因:  performSelector: withObject:方法是使用了消息发送机制, 底层调用msg_send, 会被直接调用
  •  performSelector:@selector(test) withObject:nil afterDelay: 方法底层是使用NSTimer实现, 向当前线程的runloop添加了一个timer事件, 但是子线程的runloop需要手动启动才会运行;所以不会打印;
-(void)test{
    NSLog(@"2");
}

-(void)test2{
    NSLog(@"3");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //并发队列
    dispatch_queue_t queue = dispatch_queue_create("batac.com", DISPATCH_QUEUE_CONCURRENT);
    //异步处理任务
    dispatch_async(queue, ^{
        //异步并发队列处理任务, 会开启子线程处理任务
        NSLog(@"1");
        [self performSelector:@selector(test) withObject:nil afterDelay:.0];
        [[NSRunLoop currentRunLoop] run];
        [self performSelector:@selector(test2) withObject:nil];
        NSLog(@"4");
    });
}

//打印结果:  1   2   3   4   

猜你喜欢

转载自blog.csdn.net/Batac_Lee/article/details/111490094