用RunLoop使一个线程一直运行

Posted on 2016-07-19 14:58  柠檬片  阅读(265)  评论(0)    收藏  举报
 1 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     NSLog(@"%s",__func__);
 4     
 5     /*
 6     //performSelector默认是在default模式下运行
 7 //    [self.imageView performSelector:@selector(setImage:) withObject:[UIImage imageNamed:@"abc"] afterDelay:2.0 ];
 8 
 9     [self.imageView performSelector:@selector(setImage:) withObject:[UIImage imageNamed:@"abc"] afterDelay:2.0 inModes:@[NSDefaultRunLoopMode,UITrackingRunLoopMode]];
10     
11     
12     */
13     //1.创建线程
14     //线程只能执行第一次封装的任务,不能尝试重新执行
15     XMGThread *thread = [[XMGThread alloc]initWithTarget:self selector:@selector(show) object:nil];
16     
17     //2.启动线程
18     [thread start];
19     
20     
21     
22     self.thread = thread;
23 }
24 
25 -(void)show{
26     NSLog(@"show---");
27 
28     /*
29      1.子线程的ruanloop是需要自己手动创建的
30      2.子线程的ruanloop是需要主动开启的
31      3.子线程的ruanloop里面至少要有一个source或者是timer,observer不行的
32      */
33 
34          [[NSRunLoop currentRunLoop] addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
35 
36     /*
37     NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
38     
39     [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
40     
41      */
42  
43 //    //创建一个监听对象
44 //    /*
45 //     第一个参数:分配存储空间的
46 //     第二个参数:要监听的状态 kCFRunLoopAllActivities 所有状态
47 //     第三个参数:是否要持续监听
48 //     第四个参数:优先级
49 //     第五个参数:回调
50 //     */
51 //    CFRunLoopObserverRef observer =  CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
52 //    });
53 //    
54 //    //给runloop添加监听者
55 //    /*
56 //     第一个参数:要监听哪个runloop
57 //     第二个参数:监听者
58 //     第三个参数:要监听runloop在哪种运行模式下的状态
59 //     */
60 //    CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
61 //    
62 //    CFRelease(observer);
63     
64     [[NSRunLoop currentRunLoop]run];
65 }
66 
67 - (IBAction)btnClick:(id)sender {
68     NSLog(@"btnClick");
69     [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:YES];
70     
71 //    [self.thread start];
72     
73 }
74 
75 -(void)test
76 {
77     NSLog(@"test---%@",[NSThread currentThread]);
78 }
使用示例