[消息传递之四]-NSTimer练习 倒计时

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIAlertViewDelegate>

@property (strong, nonatomic) IBOutlet UILabel *labTime;
- (IBAction)btnStart:(UIButton *)sender;

- (IBAction)btnStop:(UIButton *)sender;
@property (strong, nonatomic) IBOutlet UIButton *btnS;
@property (strong, nonatomic) IBOutlet UIButton *btnE;

@end
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    NSInteger iValue;
    NSTimer* t;
}

- (void)viewDidLoad {
    NSDate* d = [NSDate distantFuture];
    NSNumber* n = [NSNumber numberWithInteger:100];
    iValue = 5;
    SEL e =@selector(TestTimerSEL:);
    t = [[NSTimer alloc] initWithFireDate:d interval:1 target:self selector:e userInfo:n repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)TestTimerSEL:(id)Sender
{
    iValue--;
    self.labTime.text = [NSString stringWithFormat:@"%ld",iValue];
    NSInteger param = [[Sender userInfo] integerValue];
    NSLog(@"This is %ld times, sender is %ld", iValue, param);
    if (iValue == 0) {
        UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"时间到" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        [t invalidate];
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)btnStart:(UIButton *)sender {
    [t setFireDate:[NSDate date]];
    [self.btnS setEnabled:NO];
    [self.btnE setEnabled:YES];
    [self.btnS setTitle:@"继续" forState:UIControlStateNormal];
}

- (IBAction)btnStop:(UIButton *)sender {
    [self.btnS setEnabled:YES];
    [self.btnE setEnabled:NO];
    [t setFireDate:[NSDate distantFuture]];
}
@end

1,nstimer的暂停和继续是利用setfiredate来实现,退出执行是invalidate;

2,nstimer还有一个初始化方式是scheduled,直接放到runloop里面。

3,固定的执行sel格式,其中sender为timer自己,userinfo为参数。

你可能感兴趣的:(ios,NSTimer)