• 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");
    }
  • 相关阅读:
    JSP中文乱码
    Java Enum 浅析
    详解 Tomcat: The value for the useBean class attribute is invalid
    PHP+ACCESS 实例
    MySQL limit实际用法的详细解析
    JSP获取当前时间
    sql where 1=1和 0=1 的作用
    利用Quartus设计4位同步二进制加法计数器
    JSP各种路径的获取
    JSP连接MYSQL数据库
  • 原文地址:https://www.cnblogs.com/muzichenyu/p/14438910.html
Copyright © 2020-2023  润新知