• OC原理之多线程(一)


    对于如下的代码,打印结果是什么

    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            NSLog(@"1");
            [self performSelector:@selector(testhaha) withObject:nil afterDelay:.0];
            NSLog(@"3");
    });
    
    - (void)testhaha {
        NSLog(@"2");
    }

    运行之后打印如下:

    2021-02-23 23:14:10.384150+0800 KVOTest[17526:624011] 1
    2021-02-23 23:14:10.384456+0800 KVOTest[17526:624011] 3

    从打印结果来看,2并没有打印,究其原因是,performSelector:withObject:afterDelay:的本质是往Runloop中添加定时器,但是子线程中的runloop默认是没有启动的

    可通过如下的代码:

    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            NSLog(@"1");
            [self performSelector:@selector(testhaha) withObject:nil afterDelay:.0];
            [[NSRunLoop currentRunLoop] run];
            NSLog(@"3");
     });
    
    - (void)testhaha {
        NSLog(@"2");
    }

    或者直接放在主线程中执行:

    dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            NSLog(@"1");
            [self performSelector:@selector(testhaha) withObject:nil afterDelay:.0];
            [[NSRunLoop currentRunLoop] run];
            NSLog(@"3");
     });
    
    - (void)testhaha {
        NSLog(@"2");
    }
  • 相关阅读:
    [BZOJ3535][Usaco2014 Open]Fair Photography
    [LOJ#2270][BZOJ4912][SDOI2017]天才黑客
    [UOJ#122][NOI2013]树的计数
    [BZOJ4816][Sdoi2017]数字表格
    [BZOJ2154]Crash的数字表格
    [BZOJ3529][Sdoi2014]数表
    [BZOJ2820]YY的GCD
    [BZOJ2301][HAOI2011]Problem b
    [UOJ#223][BZOJ4654][Noi2016]国王饮水记
    [BZOJ4653][Noi2016]区间
  • 原文地址:https://www.cnblogs.com/muzichenyu/p/14438910.html
Copyright © 2020-2023  润新知