美文网首页
RunLoop小解

RunLoop小解

作者: 豆豆阳光啊 | 来源:发表于2017-03-02 14:11 被阅读4次

    runloop 消息处理机制,不断进行循环的一种机制,需要时就出现,不需要就沉默

    NSTimer和NSThread 都是与之相关,在使用定时器时必须加入到runloop中,定时器是不会运行。当然如果当前线程没有运行,此时的timer也是不会启动的,在app启动时,程序会默认帮我们启动一个runloop,如果我们自己重新开启一个线程,需要自己启动

    //定时器使用
    NSTimer *timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(setUI) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    //测试线程运行的状态
    NSThread *a;
    
    - (void)runLoop {
        a = [[NSThread alloc] initWithTarget:self selector:@selector(runA) object:nil];     //创建一个新的线程
        [a start];      //启动线程
        NSLog(@"runA%@",a);
    }
    
    - (void)runA {
        [NSThread detachNewThreadSelector:@selector(runB) toTarget:self withObject:nil];   //创建一个新的线程b
        NSLog(@"runA");
        while (1) {            //无限循环
            if ([[NSRunLoop currentRunLoop]runMode:@"CustomRunLoopMode" beforeDate:[NSDate distantFuture]]) {         //未来某个时间处理特定的runmode事件
                NSLog(@"%@",[NSDate distantFuture]);
                NSLog(@"B结束");
                break;
            }
        }
    }
    
    - (void)runB {
        sleep(1);
        [self performSelector:@selector(setUI) onThread:a withObject:nil waitUntilDone:YES modes:@[@"CustomRunLoopMode"]];      //直到特定事件发生才会继续运行
        NSLog(@"B运行");
    }
    
    个人初步理解
    参考知识:http://www.jianshu.com/p/3ccdda0679c1      NSTimer
                         http://www.jianshu.com/p/d04a4d574b5a    NSRunLoop
    
    

    相关文章

      网友评论

          本文标题:RunLoop小解

          本文链接:https://www.haomeiwen.com/subject/rtghgttx.html