1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSTimerの使い方

Last updated at Posted at 2017-10-02

NSTimerを使ってみた

今回、アプリの中で「スロット機能」のようなものが必要になるとのことで、初めてNSTimerを使ってみました。使い方がこれで正しいのかわかりませんが、備忘録として残します。

基本的な使い方

NSTimerの基本的な使用法は下記のように「〜秒ごとに何かのメソッドを呼び出す」という風に使うようです。
※下記では0.7秒ごとにhogeメソッドを繰り返し呼び出します。

NSTimer *timer = 
[NSTimer scheduledTimerWithTimeInterval:0.7f
target:self
selector:@selector(hoge:)
userInfo:nil 
repeats:YES];

スロット機能作成

そして今回はこのNSTimerを使って、簡易的なスロットを作ってみました。

# import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) NSTimer *timer;
@property (strong, nonatomic) NSArray *numberList;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@property (nonatomic) int getCount;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.numberList = @[@1, @2, @3, @4, @5, @6];
    
}

- (void)hoge:(NSTimer*)timer{
    if (self.getCount >= 6) {
        self.getCount = 0;
    }
    id selectCount = self.numberList[self.getCount];
    NSString *labelCountText = [NSString stringWithFormat:@"%@",selectCount];
    self.resultLabel.text = labelCountText;
    self.getCount ++;
}

- (IBAction)timerStart:(id)sender {
    [self.timer invalidate];
    self.timer =
    [NSTimer
     scheduledTimerWithTimeInterval:0.03f
     target:self
     selector:@selector(hoge:)
     userInfo:nil
     repeats:YES];
}

- (IBAction)timerStop:(id)sender {
    [self.timer invalidate];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end 

まとめ

メソッドの実行間隔を調整できるので、動的な機能を作る際は便利ですね。
今後はアニメーションなどと合わせて使ってみたいと思います。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?