美文网首页
定时器传参

定时器传参

作者: 贵哥jk | 来源:发表于2016-05-18 11:47 被阅读127次

开启一个需要传递参数的定时器

先上代码

- (void)creatTimer{
  //  id userInfo = @"贵哥jk";
  //  id userInfo = @{@"姓名": @"贵哥jk", @"email":@"942513675@qq.com"};
  //  id userInfo = @10;
    
    id userInfo = [UIButton new];
    ((UIButton *)userInfo).tag = 1000;
    
    NSTimeInterval time = 0.5;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(timerSelector:) userInfo:userInfo repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)timerSelector:(NSTimer *)timer{
    id userInfo = timer.userInfo;
    NSLog(@"%@",userInfo);

    UIButton *btn = userInfo;
    NSLog(@"%ld",btn.tag);

    if (@"条件判断") {
        [timer invalidate];
        timer = nil;
    }
}

解析

  • 类方法:scheduledTimerWithTimeInterval:(NSTimeInterval) time target:(id) aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;可以传递一个 id 类型的参数
  • 在传递参数的时候是以 NSTimer 的实例对象的 userInfo 属性传递的
  • 注意在 timerSelector: 方法中将 userInfo 转化为传递的类型就可以了

相关文章

网友评论

      本文标题:定时器传参

      本文链接:https://www.haomeiwen.com/subject/pmhwrttx.html