-(void)testRunLoopOnMainThread
{
NSLog(@"start new thread …");
[NSThreaddetachNewThreadSelector:@selector(runOnNewThread)toTarget:selfwithObject:nil];
while(!end) {
NSLog(@"runloop begin");
[[NSRunLoopcurrentRunLoop]runMode:NSDefaultRunLoopModebeforeDate:[NSDatedistantFuture]];
NSLog(@"runloop end");
}
NSLog(@"test runloop end");
}
-(void)runOnNewThread{
NSLog(@"run for new thread");
sleep(5);
dispatch_async(dispatch_get_main_queue(), ^{end=YES;});
NSLog(@"new thread end");
}
上述代码运后打印如下
2016-04-26 15:05:33.526 test[20305:129328] start new thread …
2016-04-26 15:05:33.528 test[20305:129328] runloop begin
2016-04-26 15:05:33.528 test[20305:129369] run for new thread
2016-04-26 15:05:38.534 test[20305:129328] runloop end.
2016-04-26 15:05:38.534 test[20305:129369] new thread end.
2016-04-26 15:05:38.535 test[20305:129328] testrunloop finish
若多线程执行期间用户点击了其他按钮则将由如下输出
2016-04-26 15:08:00.105 test[20573:131645] start new thread …
2016-04-26 15:08:00.106 test[20573:131645] runloop begin
2016-04-26 15:08:00.107 test[20573:131797] run for new thread
2016-04-26 15:08:00.976 test[20573:131645] runloop end.
2016-04-26 15:08:00.977 test[20573:131645] runloop begin
2016-04-26 15:08:00.979 test[20573:131645] runloop end.
2016-04-26 15:08:00.980 test[20573:131645] runloop begin
2016-04-26 15:08:00.980 test[20573:131645] runloop end.
2016-04-26 15:08:00.980 test[20573:131645] runloop begin
2016-04-26 15:08:01.110 test[20573:131645] runloop end.
2016-04-26 15:08:01.111 test[20573:131645] runloop begin
2016-04-26 15:08:01.112 test[20573:131645] user press a button
2016-04-26 15:08:01.114 test[20573:131645] runloop end.
2016-04-26 15:08:01.114 test[20573:131645] runloop begin
2016-04-26 15:08:01.114 test[20573:131645] runloop end.
2016-04-26 15:08:01.114 test[20573:131645] runloop begin
2016-04-26 15:08:01.585 test[20573:131645] runloop end.
2016-04-26 15:08:01.585 test[20573:131645] runloop begin
2016-04-26 15:08:05.109 test[20573:131645] runloop end.
2016-04-26 15:08:05.109 test[20573:131797] new thread end.
2016-04-26 15:08:05.109 test[20573:131645] testrunloop finish
从上述打印可以看出 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]本质上是runloop消息的一个人为添加的监听点。当runloop在监听的mode上没有收到任何消息时是不启动的,当收到任何消息时都会去到这里跑一圈看看,若满足条件就执行完毕了向下了,不会阻塞主线程,但是若在某种情况下条件永远无法满足,后面的代码也无法执行
总之并不是很好用,如果能用别的方法代替,还是不用这个为好。
----另外一处容易出错的问题:
如果dispatch_async(dispatch_get_main_queue(), ^{end=YES;});词句变更为end=YES;会怎样
答案是NSLog(@"test runloop end");始终都不会打印,直到用户做了其他操作,比如点击了一个别的按钮。