在编程过程中,总有需要使用到定时器的时候,Object-C中有专门的NSTimer:
@interface NSTimer : NSObject
//初始化,最好用scheduled方式初始化,不然需要手动addTimer:forMode: 将timer添加到一个runloop中。
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (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;
- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep;
- (void)fire; //立即触发定时器
- (NSDate *)fireDate;//开始时间
- (void)setFireDate:(NSDate *)date;//设置fireData,其实暂停、开始会用到
- (NSTimeInterval)timeInterval;//延迟时间
- (void)invalidate;//停止并删除
- (BOOL)isValid;//判断是否valid
- (id)userInfo;//通常用nil
@end
使用NSTimer比需要做到:
1. 定时器的selector实现:
- (void)handleTimer: (NSTimer *) timer
{
NSDictionary *currentAudioTrack = [_player getCurrentAudioTrack];
for (id key in currentAudioTrack) {
NSLog(@"key: %@ , value: %@ ", key, [currentAudioTrack objectForKey:key]);
}
if (1 == [currentAudioTrack[@"type"] integerValue]) {
NSDictionary *nonDolbyLang = @{@"lang":@"1", @"type":@"0"};
[_player switchAudioStream:nonDolbyLang];
}else {
NSDictionary *dolbylang = @{@"lang":@"1", @"type":@"1"};
[_player switchAudioStream:dolbylang];
}
}
2. 定时器target以及定义实现:
- (void)setupswitchAudioTimer{
NSTimer *switchAudioTimer = [NSTimer scheduledTimerWithTimeInterval: 60.0 // 间隔60s执行一次handleTimer
target: self
selector: @selector(handleTimer:)
userInfo: nil
repeats: YES];
[switchAudioTimer setFireDate:[NSDate distantPast]];
}
3. 开启定时器即调用此定时器:
[self setupswitchAudioTimer];