iOS中定时器NSTimer的使用

时间:2022-05-18 03:50:25
  • iOS中定时器NSTimer的使用
  • 创建 NSTimer
  • iOS中定时器NSTimer的使用

    1、初始化 

    + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; 

    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; 

    注:不用scheduled方式初始化的,需要手动addTimer:forMode: 将timer添加到一个runloop中。 

      而scheduled的初始化方法将以默认mode直接添加到当前的runloop中. 

      

    举例: 

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO]; 

    或 

    NSTimer *myTimer = [NSTimer  timerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:)userInfo:nilrepeats:NO];

    [[NSRunLoop  currentRunLoopaddTimer:myTimerforMode:NSDefaultRunLoopMode];

      

    2、触发(启动) 

    当定时器创建完(不用scheduled的,添加到runloop中后,该定时器将在初始化时指定的timeInterval秒后自动触发。 

      

    可以使用-(void)fire;方法来立即触发该定时器; 

    注:You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived. 

    在重复执行的定时器中调用此方法后立即触发该定时器,但不会中断其之前的执行计划; 

    在不重复执行的定时器中调用此方法,立即触发后,就会使这个定时器失效。 

      

    3、停止 

    - (void)invalidate; 

    这个是唯一一个可以将计时器从runloop中移出的方法。 

      

    注: 

    NSTimer可以精确到50-100毫秒. 

    NSTimer不是绝对准确的,而且中间耗时或阻塞错过下一个点,那么下一个点就pass过去了. 

      

    延时函数和Timer的使用

    iOS中定时器NSTimer的使用
    //延时函数: [NSThread sleepForTimeInterval:5.0]; //暂停5s. //Timer的使用: NSTimer *connectionTimer; //timer对象 //实例化timer self.connectionTimer=[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop]addTimer:self.connectionTimer forMode:NSDefaultRunLoopMode]; //用timer作为延时的一种方法 do{
    [[NSRunLoopcurrentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]];
    }while(!done); //timer调用函数 -(void)timerFired:(NSTimer *)timer{
    done =YES;
    }
    iOS中定时器NSTimer的使用


      

    转自:http://magicalboy.com/objective_c_nstimer_usage/#comment-45 

    创建 NSTimer 

    1. Scheduled Timers & Using Selector 

      

    -  ( IBAction ) startOneOffTimer: sender  {       [ NSTimer  scheduledTimerWithTimeInterval: 2.0                target: self                selector: @selector ( targetMethod: )                userInfo: [ self  userInfo ]                repeats: NO ];  }view raw gistfile1.m This Gist brought to you by  GitHub

      

      如上,如果没有重复执行的timer相当于  

    [self performSelector:@selector(targetMethod:) withObject:nil afterDelay:2.0]; 

        

      

    // declcare@property  ( assign )  NSTimer  * repeatingTimer ;  // implements-  ( IBAction ) startRepeatingTimer: sender  {           NSTimer  * timer  =  [ NSTimer  scheduledTimerWithTimeInterval: 0.5                                 target: self  selector: @selector ( timerFireMethod: )                                 userInfo: [ self  userInfo ]  repeats: YES ];       self . repeatingTimer  =  timer ;  }  -  ( IBAction ) stopRepeatingTimer: sender  {       [ repeatingTimer  invalidate ];       self . repeatingTimer  =  nil ;  }view raw gistfile1.m This Gist brought to you by  GitHub

      

    1. Unscheduled Timers & Using Invocation 

      

    // declare @property (retain) NSTimer *unregisteredTimer;       // implements - (IBAction)createUnregisteredTimer:sender {       NSMethodSignature *methodSignature = [self methodSignatureForSelector:@selector(invocationMethod:)];       NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];       [invocation setTarget:self];       [invocation setSelector:@selector(invocationMethod:)];       NSDate *startDate = [NSDate date];       [invocation setArgument:&startDate atIndex:2];         NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 invocation:invocation repeats:YES];       self.unregisteredTimer = timer;         - (IBAction)startUnregisteredTimer:sender {       if (unregisteredTimer != nil) {           NSRunLoop *runLoop = [NSRunLoop currentRunLoop];           [runLoop addTimer:unregisteredTimer forMode:NSDefaultRunLoopMode];       }     - (IBAction)stopUnregisteredTimer:sender {       [unregisteredTimer invalidate];       self.unregisteredTimer = nil;   }