MRC下計時器

NSTimer,計時器,作用:每隔多少秒執行相應的方法

   
//創建方法1
   
    [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(start:) userInfo:nil repeats:YES];
    [NSTimer scheduledTimerWithTimeInterval:7.0 target:self selector:@selector(stop:) userInfo:nil repeats:YES];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(print:) userInfo:@"ASXD" repeats:YES];
   
   
//創建方法2
   
    NSDate *fiveDate = [NSDate dateWithTimeIntervalSinceNow:5];
    NSTimer *timer2 = [[NSTimer alloc] initWithFireDate:fiveDate interval:1 target:self selector:@selector(start:) userInfo:nil repeats:YES];
   
   
每個線程(thread)中都有一個事件循環(NSRunLoop),來時時判斷是否執行某些事件或方法
   
加入到事件循環中,通過init方式創建的timer不能執行,需要加入到NSRunLoop
    [[NSRunLoop currentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
    [timer2 release];
   
   //立即執行第一次操作
    [timer2 fire];
    //停止計時器
    [timer2 invalidate];
   
   
//創建方法3
    NSTimer *timer3 = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(print:) userInfo:nil repeats:YES];
    //添加到主線程的事件循環中
    [[NSRunLoop mainRunLoop] addTimer:timer3 forMode:NSDefaultRunLoopMode];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章