timer与observer在runloop中

 1 @interface ViewController ()
 2 
 3 @end
 4 
 5 @implementation ViewController
 6 
 7 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 8 {
 9     
10     [self timer1];
11     
12 //    [self timer2];
13 
14     
15     /*
16     这种写法错误,因为子线程中还没runloop,子线程中的runloop要手动创建,手动开启
17     [[[NSOperationQueue alloc]init] addOperationWithBlock:^{
18         
19         [self timer2];
20     }];
21      */
22 }
23 
24 - (void)timer2
25 {
26     //创建定时器
27     //这个方法需要手动把当前的timer添加到runloop中,并且制定runloop运行模式
28     NSTimer *tiemr = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:YES];
29     
30     
31     [[NSRunLoop currentRunLoop]addTimer:tiemr forMode:NSRunLoopCommonModes];
32 }
33 
34 
35 - (void)timer1
36 {
37     //创建定时器,每隔两秒就调用task 这个方法
38     //该方法内部会自动将创建的定时器对象添加到当前的runloop中,指定的运行模型为默认
39     [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:YES];
40 }
41 
42 
43 - (void)task
44 {
45     NSLog(@"task---%@----%@",[NSRunLoop currentRunLoop].currentMode,[NSThread currentThread]); 
//打印: task---kCFRunLoopDefaultMode----<NSThread: 0x7f7fb2c04810>{number = 1, name = main} 46 }

 

posted @ 2016-08-24 21:16  东爵  阅读(119)  评论(0)    收藏  举报