NSRunLoop Demo

舉個小例子,NSThread如何添加NSRunLoop。

    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(doThread) object:nil];
    [thread start];
    [self performSelector:@selector(doCheck) onThread:thread withObject:nil waitUntilDone:NO];
    [self performSelector:@selector(doCheck1) onThread:thread withObject:nil waitUntilDone:NO];

-(void) doCheck{
    
    NSLog(@"current thread:%@", [NSThread currentThread].name);
}

-(void) doCheck1{
    
    NSLog(@"current thread 1:%@", [NSThread currentThread].name);
}
     
-(void) doThread{
    
    NSLog(@"2");
    [[NSThread currentThread] setName:@"TestInfo"];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
    [runLoop run];
    NSLog(@"3");
}


日誌顯示兩個動作都放生在線程TestInfo中。

2015-12-07 17:34:51.249 TestRunLoop[3020:170027] 2
2015-12-07 17:34:51.251 TestRunLoop[3020:170027] current thread:TestInfo
2015-12-07 17:34:51.252 TestRunLoop[3020:170027] current thread 1:TestInfo


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章