定时器NSTimer的简单使用

来源:互联网 发布:java解压gz文件 编辑:程序博客网 时间:2024/04/29 09:09

一,添加NSTmer属性

@property (nonatomic, nonnull,strong)NSTimer *timer;

二,对属性进行懒加载并添加处理事件的方法

-(NSTimer *)timer{    if (!_timer) {        //添加响应事件        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];        //将时间启动器添加到runloop中启动        [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];    }    return _timer;}

三,启动定时器

-(void)viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    //启动定时器    [self timer];}

四,处理事件

-(void)nextImage{    _timerNum --;    NSLog(@"%zd",_timerNum);    NSString *str = [NSString stringWithFormat:@"%zd:秒",_timerNum];    _timerLabel.text = str;    if (_timerNum == 0) {        [self starLocation:nil];        _timerNum = Num;    }}

以上是最简单的NSTimer的使用方法,往后会对其进行深入研究!

0 0