iOS之创建一个常驻线程

// 当创建一个线程,并且希望它一直存在时,但往往我们创建的线程都是执行完成之后也就停止了,不能再次利用,那么如何创建一个线程可以让他可以再次工作呢,这个时候就需要使用到RunLoop了。下面的是我写的一个例子:
#import "LongThreadDemoController.h" @interface LongThreadDemoController () @property (nonatomic, strong) NSThread *thread; @end @implementation LongThreadDemoController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.title = @"常驻线程Demo"; } - (void)threadRunloopPoint:(id)__unused object{ NSLog(@"%@",NSStringFromSelector(_cmd)); @autoreleasepool { [[NSThread currentThread] setName:@"changzhuThread"]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; //// 这里主要是监听某个 port,目的是让这个 Thread 不会回收 [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; [runLoop run]; } } - (NSThread *)thread{ if(!_thread){ _thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRunloopPoint:) object:nil]; [_thread start]; } return _thread; } - (void)test{ NSLog(@"%s",__func__); } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO modes:@[NSDefaultRunLoopMode]]; }

  

 

posted @ 2015-09-14 11:45  OHeroJ  阅读(3501)  评论(0编辑  收藏  举报