想要做一個計時器 (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 範例:
[iOS] Swift how to use NSTimer background?
https://stackoverflow.max-everyday.com/2018/01/ios-swift-how-to-use-nstimer-background/