核心代碼
//添加一個source到runloop中疚漆,防止runloop無線循環(huán)消耗cpu剧蹂,(原理:當runloop,run的時候發(fā)現有source的時候不會退出進行掛起帖鸦,等待系統(tǒng)的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");
}
//點擊事件(將一個方法加入后臺執(zhí)行)劫拢,(如果不加入runloop的方法,只會執(zhí)行一次)
- (IBAction)onFire:(id)sender {
[self performSelector:@selector(fireSelector:)
onThread:_thread
withObject:nil
waitUntilDone:NO];
}
- (void)fireSelector:(id)arg
{
NSLog(@"fire in the hole");
}