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