实现定时器功能的几种方式

2017-12-22  本文已影响0人  锦鲤跃龙
  1. nsrunLoop
  2. GCD
  3. RAC

NsrunLoop

NSRunLoop是IOS消息机制的处理模式

  • 一条线程对应一个RunLoop,主线程的RunLoop默认已经创建好了, 而子线程的需要我们自己手动创建
- 获取主线程对应的RunLoop对象mainRunLoop/CFRunLoopGetMain(  ***[NSRunLoop mainRunLoop]***)
- 获取当前线程对应的RunLoop对象currentRunLoop/CFRunLoopGetCurrent (  ***[NSRunLoop currentRunLoop]***)
-(void)demo1
{

    //事件 交给谁处理?Runloop
    NSTimer *timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeMethod) userInfo:nil repeats:YES];

  [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
}
//所有被"标记"common的模式都可以运行,UITrackingRunLoopMode和kCFRunLoopDefaultMode都被标记为了common模式,所以只需要将timer的模式设置为forMode:NSRunLoopCommonModes,就可以在默认模式和追踪模式都能够运行


-(void)timeMethod
{

    NSLog(@"能不能执行!");
    
    
}

NsrunLoop的mode

GCD

///将定时器设置在主线程
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    
    //2设置定时器每一秒执行一次 GCD时间事件 1000000000 
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0);
    3设置定时器执行的动作
    dispatch_source_set_event_handler(timer, ^{
        NSLog(@"----%@",[NSThread currentThread]);
        NSLog(@"执时钟事件");
    });
    
    //4.启动定时器
    dispatch_resume(timer);
    _timer = timer;//设置一个变量存储timer 否则执行一次就被释放了,是因为内存管理的原因,使用了dispatch_source_create方法,这种方法GCD是不会帮你管理内存的

dispatch_source_create

dispatch_source_create(dispatch_source_type_t type,
 uintptr_t handle,
 unsigned long mask,
 dispatch_queue_t _Nullable queue)

dispatch_source_set_timer

dispatch_source_set_timer(dispatch_source_t source,
 dispatch_time_t start,
 uint64_t interval,
 uint64_t leeway);

dispatch_source_set_event_handler

dispatch_source_set_event_handler(dispatch_source_t source,
 dispatch_block_t _Nullable handler)

dispatch_resume

dispatch_resume(_timer)

定时器创建完成并不会运行,需要主动去触发,也就是调用上述方法。

调度源提供了源事件的处理回调,同时也提供了取消源事件处理的回调,使用非常方便。

dispatch_source_set_cancel_handler(dispatch_source_t source,
 dispatch_block_t _Nullable handler)

这个方法参数一看就明白了

RAC

  RACDisposable* disble =   [[RACSignal interval:1.0 onScheduler:[RACScheduler scheduler]]subscribeNext:^(NSDate * _Nullable x) {
        
        NSLog(@"%@",[NSThread currentThread]);
        
    }];
    
    [disble dispose];//取消  比如点击什么事件取消
    

上一篇 下一篇

猜你喜欢

热点阅读