NSTimerでカウントダウンタイマー。

前回の記事でNSTimerは一定時間ごとにアクションを起こすものだと書いた。
viewDidLoadメソッドに入れておけば画面が表示されて一定時間後にアラートを出したり広告を変えたりするには便利だ。

しかし、カウントダウンタイマーとして使うにはviewDidLoadメソッドに入れると使いにくい。
何か方法があるのかもしれないがよく判らん。

簡単にできる方法としてはメソッドの中で動作させるのが良いだろう。

参考にさせて頂いたサイトはコチラ。
Objective-C – NSTimerの基本的な使い方 – Qiita

#import "ViewController.h"

@interface ViewController ()
{
    int count;
    NSTimer *timer_;
}
@property (weak, nonatomic) IBOutlet UILabel *timeHyouji2;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)timeStart2:(UIButton *)sender {
    //タイマーが動いていないときにタイマー開始
    if (![timer_ isValid]) {
        //[timer_ fire];
        count = 30;    
        self.timeHyouji2.text = [NSString stringWithFormat:@"%d",count];
        timer_ = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(time:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}

    
-(void)time:(NSTimer*)timer{
    NSLog(@"%d", count);
    count -= 1;
    self.timeHyouji2.text = [NSString stringWithFormat:@"%d",count];
    //タイマーが有効かどうか
    NSString *str = [timer_ isValid] ? @"yes" : @"no";
    NSLog(@"isValid:%@", str);

    if (count <= 0.0) {
        [timer_ invalidate];
    }

}

@end

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です