NSTimer 常用於定時執行,例如倒數、輪詢或動畫更新。使用時要注意初始化、觸發、失效與暫停。
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTime:) userInfo:nil repeats:YES];[timer fire];[timer invalidate];
timer = nil;timer 一旦 invalidate,就不能再次使用,若要繼續,需要重新建立。
[timer setFireDate:[NSDate distantFuture]];
[timer setFireDate:[NSDate distantPast]];NSDictionary *dic = [NSDictionary dictionaryWithObject:@"1" forKey:@"animIndexPath"];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTime:) userInfo:dic repeats:YES];
-(void)changeTime:(NSTimer *)tme {
NSString *value = [[tme userInfo] objectForKey:@"animIndexPath"];
}if ([timer isValid]) {
[timer invalidate];
timer = nil;
}