- (void)threadTest { NSLog(@"--%@--", [NSThread currentThread]); [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode]; [[NSRunLoop currentRunLoop] run]; }
一个线程对应一个RunLoop,RunLoop里有若干个mode, 每个mode都有自己的内容, Source/Timer/Observer等等
上面代码就相当于给当前RunLoop添加了一个内容为Source的mode. 而RunLoop有了mode才会有效果
注意:mode里必须有内容 Source, Timer, Observer都可以
performSelector相当于sourse, 给mode里添加source
要让RunLoop跑起来, 必须给其添加一个有内容的mode, 而且必须让他run
RunLoop跑起来就相当于一个while死循环,后面代码不会执行
子线程中的timer与RunLoop
- (void)viewDidLoad { [super viewDidLoad]; _thread = [[YQThread alloc] initWithTarget:self selector:@selector(threadTest) object:nil]; [_thread start]; } - (void)threadTest { [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(TimerTest) userInfo:nil repeats:YES]; } - (void)TimerTest { NSLog(@"----%@-----", [NSThread currentThread]); }
只有主线程的RunLoop会自动开启, 而子线程需要手动开启