185,NSTimer类的应用

来源:互联网 发布:淘宝店铺旺旺名怎样看 编辑:程序博客网 时间:2024/06/08 06:15

#import "ViewController.h"


@interface ViewController ()

@property (weak, nonatomic) IBOutletUILabel *counter;

@property (nonatomic,strong)NSTimer *mytimer;


@end


@implementation ViewController


- (IBAction)start:(UIButton *) sender{

    //第一种创建时钟的方法:

    /**

     *  scheduledTimerWithTimeInterval 间隔时间

     *  selector 循环执行方法

     *  repeats 是否重复

     *  默认模型为NSDefaultRunLoopMode,即滚动的时候,就不会监听

     *  其他事件了

     */

    

    //    if (self.mytimer == nil) {

    //        self.mytimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateCounter) userInfo:nil repeats:YES];

    //    }

    //第二种创建时钟的方法跟第一种等同,模式为NSDefaultRunLoopMode

    //    self.mytimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateCounter) userInfo:nil repeats:YES];

    //    [[NSRunLoop currentRunLoop] addTimer:self.mytimer forMode: NSDefaultRunLoopMode];

    //第三种创建时钟的方法,模式为NSRunLoopCommonModes,为运行循环的普通模式,事件之间互不干扰

    self.mytimer = [NSTimertimerWithTimeInterval:1target:selfselector:@selector(updateCounter)userInfo:nilrepeats:YES];

    [[NSRunLoopcurrentRunLoop]addTimer:self.mytimerforMode:NSRunLoopCommonModes];

    

}


-(void)updateCounter{

    int now = self.counter.text.intValue;

    if (--now < 0) {

        [self.mytimerinvalidate];

        self.mytimer =nil;

        

        //实例化一个警告框对象

        UIAlertController *alertController = [UIAlertControlleralertControllerWithTitle:@"开始"message:@"开始了..."preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *confirm = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *_Nonnull action) {

            NSLog(@"你点了确定按钮了");

        }];

        [alertController addAction:confirm];

        [selfpresentViewController:alertControlleranimated:truecompletion:^{

            NSLog(@"已经开始了!");

        }];

        

    }else{

        self.counter.text = [NSStringstringWithFormat:@"%i",now];

    }

}


- (IBAction)pause:(UIButton *) sender {

    /**

     *  invalidateNSTimer唯一的停止时钟的方法,注意的是,停止时钟,只会让时钟对

     *  象休停,而不是被销毁。一旦停止时钟,那么,就需要再实例化新的时钟对象,才能

     *  继续操作下去。

     */

    [self.mytimerinvalidate];

    self.mytimer =nil;

}



- (IBAction)stop:(UIButton *)sender {

    [self.mytimerinvalidate];

    self.mytimer =nil;

    self.counter.text =@"10";

}


@end

//注意:NSTimer 计时并不精准,只能用其他方法来计算精准时间,NSTimer适用于计算时分跨度大的间隔时间


0 0
原创粉丝点击