核心代码
//添加一个source到runloop中,防止runloop无线循环消耗cpu,(原理:当runloop,run的时候发现有source的时候不会退出进行挂起,等待系统的source把这个runloop叫醒就行。)
NSPort *port=[NSMachPort port];
[[NSRunLoop currentRunLoop] addPort:port forMode:NSDefaultRunLoopMode];
while (![[NSThread currentThread] isCancelled]) {
[[NSRunLoop currentRunLoop] run];
}
Demo
- (void)viewDidLoad {
[super viewDidLoad];
// 开启一个线程
_thread = [[NSThread alloc] initWithTarget:self
selector:@selector(threadFunction:) object:nil];
[_thread start];
}
- (void)threadFunction:(id)arg
{
NSLog(@"thread begin");
NSPort *port = [NSMachPort port];
[[NSRunLoop currentRunLoop] addPort:port
forMode:NSDefaultRunLoopMode];
while (![[NSThread currentThread] isCancelled])
{
NSLog(@"runloop begin");
[[NSRunLoop currentRunLoop] run];
NSLog(@"runloop end");
}
NSLog(@"thread end");
}
//点击事件(将一个方法加入后台执行),(如果不加入runloop的方法,只会执行一次)
- (IBAction)onFire:(id)sender {
[self performSelector:@selector(fireSelector:)
onThread:_thread
withObject:nil
waitUntilDone:NO];
}
- (void)fireSelector:(id)arg
{
NSLog(@"fire in the hole");
}