码迷,mamicode.com
首页 > 移动开发 > 详细

iOS: 常驻线程

时间:2020-06-19 16:03:09      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:imei   block   修改   cti   number   nslog   ber   void   sda   

如何开启

首先开启一个线程:

 1 @property (nonatomic, strong) NSThread *thread;
 2 
 3 - (IBAction)startAction:(id)sender {
 4     NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];
 5     thread.name = @"com.live.thread";
 6     // 开启子线程
 7     [thread start];
 8     self.thread = thread;
 9 }
10 
11 - (void)start {
12     NSLog(@"start----%@",[NSThread currentThread]);
13 }
14 
15 - (IBAction)taskAction:(id)sender {
16     /*
17      如果设置wait为YES:等待当前线程执行完以后,主线程才会执行aSelector方法;
18      设置为NO:不等待当前线程执行完,就在主线程上执行aSelector方法。
19      如果,当前线程就是主线程,那么aSelector方法会马上执行。
20      */
21     [self performSelector:@selector(task) onThread:self.thread withObject:nil waitUntilDone:YES];
22     
23 }
24 
25 - (void)task {
26     NSLog(@"task----%@",[NSThread currentThread]);
27 }

根据代码可知,执行startAction,打印

start----<NSThread: 0x280b84c40>{number = 6, name = com.live.thread}

我们知道一个线程执行完任务后就会自动销毁,再次调用此线程去执行任务即会报错:

技术图片

所以我们一般启动Runloop来使线程常驻,修改代码如下:

1 - (void)start {
2     NSLog(@"start----%@",[NSThread currentThread]);
3     @autoreleasepool {
4         do {
5             [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
6         } while (YES);
7     }
8 }

便可成功执行task:

start----<NSThread: 0x2807d5300>{number = 7, name = com.live.thread}

task----<NSThread: 0x2807d5300>{number = 7, name = com.live.thread}

 

如何停止

代码如下:

 1 @property (nonatomic, assign) BOOL cancelled;
 2 
 3 - (IBAction)stopAction:(id)sender {
 4     [self performSelector:@selector(stop) onThread:self.thread withObject:nil waitUntilDone:NO];
 5 
 6     NSLog(@"退出runLoop");
 7 }
 8 
 9 - (void)start {
10     NSLog(@"start----%@",[NSThread currentThread]);
11     @autoreleasepool {
12         do {
13             [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
14         } while (!self.cancelled);
15     }
16 }
17 
18 - (void)stop {
19     self.cancelled = YES;
20 }

添加一个flag操控,执行stopAction后,再次操作task便又会报错,说明Runloop停止了

 

iOS: 常驻线程

标签:imei   block   修改   cti   number   nslog   ber   void   sda   

原文地址:https://www.cnblogs.com/Walsh/p/13163288.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!