Object-C NSTimer定时器使用

在编程过程中,总有需要使用到定时器的时候,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];


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值