[iOS] 計時器 (Timer)
阿新 • • 發佈:2018-12-27
想要做一個計時器 (Timer),可以怎麼做?使用NSTimer,每隔一秒鐘更新一次秒數,就這麼簡單!
- (
void
)viewDidLoad
{
[super viewDidLoad];
// 設定Timer,每過1秒執行方法
self.accumulatedTime = 0;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
}
-(
void
)updateTime:(NSTimer *)timer
{
self. accumulatedTime++;
NSLog(@
"accumulatedTime:%f"
,self. accumulatedTime);
}
上面是有傳Timer 為引數的寫法,如果沒有要傳 Timer 進去,就拿掉 : 即可,我正使用的中的範例:
@property (weak, nonatomic) NSTimer *checkCameraStatusTimer;//頁面將要進入前臺,開啟定時器 -(void)viewWillAppear:(BOOL)animated { //開啟定時器 self.checkCameraStatusTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkcamerastates) userInfo:nil repeats:YES]; [self.checkCameraStatusTimer fire]; } //頁面消失,進入後臺不顯示該頁面,關閉定時器 -(void)viewDidDisappear:(BOOL)animated { //關閉定時器 [self.checkCameraStatusTimer invalidate]; } -(void)checkcamerastates { // TODO: here.. }
Swift 範例: