1 @interface ViewController ()
2
3 /** 线程 */
4 @property(nonatomic,strong)NSThread *thread ;
5 @end
6
7 @implementation ViewController
8 - (IBAction)create:(id)sender { //从storyboard 中拖过程的按钮(创建线程)
9
10 //01创建线程对象
11 NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(task1) object:nil];
12
13 //02开启子线程
14 [thread start];
15 self.thread = thread;
16 }
17
18 - (void)task1
19 {
20
21 NSLog(@"task1----%@",[NSThread currentThread]);//子线程
22
23
24 /**
25 01 这里我们要明确一个知识点:线程的生命周期与任务有关,任务执行完毕,它会自动销毁,就算你用强指针指着它也还是不行.
26 02 如果想让线程不死,可以让任务不结束,我们可以仿苹果做法,让线程有任务就执行,没执行就休眠.
27 03 我们知道runloop: 只要runloop 中有model, model中有timer/source/observer/ 它就不会退出.
28 04 在开发中如果是为了让一个任务不结束,我们很少创建一个timer,因为一个timer就又涉及到时间,任务这样.
29 05 在开发中我们一般选择source 的方式:开一个端口
30 06 以上这些做法都是在结束中执行,因为你是要任务不结束
31 */
32
33 //代码实现
34 //01创建子线程的runloop
35 NSRunLoop *currentRunloop = [NSRunLoop currentRunLoop];
36
37 //02给当前子线程添加端口
38 [currentRunloop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
39
40 //03启动runloop(子线程的runloop需手动启动)
41 [currentRunloop run];
42 }
43
44 - (IBAction)goOn:(id)sender { //从storyboard 中拖过程的按钮(让子线程继续执行任务)
45
46
47 //继续执行任务
48 [self performSelector:@selector(task2) onThread:self.thread withObject:nil waitUntilDone:YES];
49
50
51 }
52
53 - (void)task2
54 {
55 NSLog(@"task2----%@",[NSThread currentThread]);//子线程
56 }