舉個小例子,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