zoukankan      html  css  js  c++  java
  • 四个简单易用的demo,关于iOS定时器和延时的,非常好用。

    1,延时执行(不可重复)

    [objc] view plain copy
    
    /** 
     ** delay 不可重复 
     **/  
    - (void)timerMethodA  
    {  
        [self performSelector:@selector(methodAEvent)  
                   withObject:nil  
                   afterDelay:2.0f];//延时时间  
    }  
      
    - (void)methodAEvent  
    {  
        NSLog(@"-- method_A");  
    }  


    效果我直接截取控制台的日志了,就不做UI了。

    2,用NSTimer执行定时和延时(可重复)

    [objc] view plain copy
    
    /** 
     ** timer 可重复 
     **/  
    - (void)timerMethodB  
    {  
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f  //间隔时间  
                                                  target:self  
                                                selector:@selector(methodBEvnet)  
                                                userInfo:nil  
                                                 repeats:YES];  
    }  
      
    - (void)methodBEvnet  
    {  
        count++;  
        NSLog(@"-- Method_B count: %d", count);  
          
        if (count >= 5) {  
            [_timer invalidate];    //重复5次,timer停止  
            NSLog(@"-- end");  
        }  
    } 

    3,用dispatch_source_set_timer执行定时(可重复)

    [objc] view plain copy
    
    /** 
     ** dispatch_time 可重复 
     **/  
    - (void)timerMethodC  
    {  
        __block int i = 0;  
        CGFloat duration = 1.0f;   //间隔时间  
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);  
          
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, duration * NSEC_PER_SEC, 0);  
        dispatch_source_set_event_handler(timer, ^{  
              
            i++;  
            if (i > 5) {  
                dispatch_source_cancel(timer);  //执行5次后停止  
                NSLog(@"-- end");  
            }else{  
                NSLog(@"-- Method_C i:%d", i);  
            }  
        });  
        dispatch_resume(timer);  
    }  

    4,用dispatch_after执行延时(不可重复)

    [objc] view plain copy
    
    /** 
     ** dispatch_time 不可重复 
     **/  
    - (void)timerMethodD  
    {  
        CGFloat delayTime = 2.0f;   //延时时间  
        dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime *NSEC_PER_SEC));  
        dispatch_after(timer, dispatch_get_main_queue(), ^{  
            NSLog(@"-- Method_D time:%@", [NSDate date]);  
        });  
                                                
    }  

    文章最后奉上demo

    http://download.csdn.net/detail/xiongbaoxr/9417374

  • 相关阅读:
    load data to matlab
    Apriori algorithm
    LOGIN Dialogue of Qt
    Methods for outlier detection
    MFC改变对话框背景色
    g++宏扩展
    Some key terms of Data Mining
    Qt QLabel 显示中文
    How To Debug a Pyhon Program
    C++命名规范
  • 原文地址:https://www.cnblogs.com/henusyj-1314/p/8116976.html
Copyright © 2011-2022 走看看