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]]; }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM