0

I am making a Simon Says app to learn more about Objective C.

My SimonSaysViewController has 4 buttons. Their image needs to change accordingly when the pattern is being shown to the user.

A fixed interval timer will be absolutely fine.

I just cannot seem to find an example.

I basically would want a sort of setup like:

TimerTicked callback when I can do the image swapping logic.

Ideally, the TimerTicked method would be a method of my SimonSaysViewController.

How would this be done?

Thanks

jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • Here's pretty good example of using NSTimer class: http://stackoverflow.com/questions/12052914/how-can-i-start-and-stop-nstimer – Igor Nov 13 '13 at 22:22

2 Answers2

3

NSTimer is your friend! Add an NSTimer property to your SimonSaysViewController.

@property (strong, nonatomic) NSTimer *tickTockTimer;

Depending on when you want the timer to start, you'll want to set up the timer then. Say you wanted the timer to start when the view first appears:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.tickTockTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
}

Then implement the timerFired method and do what you need there.

- (void)timerFired:(NSTimer *)timer {
    //change the image.
}

Don't forget to invalidate the timer when you are done.

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}
Serghei Pogor
  • 108
  • 1
  • 10
Lance
  • 8,872
  • 2
  • 36
  • 47
  • 1
    Yep, this code is what you need Milo. Lance, please add [self.tickTockTimer invalidate] because it's pretty important part of NSTimer. – Igor Nov 13 '13 at 22:25
  • Would you be so kind as to explain what strong nonatomic does and why you are not managing memory? – jmasterx Nov 13 '13 at 22:25
  • Thanks, updated my answer to include `invalidate` – Lance Nov 13 '13 at 22:26
  • Oh, looks like you added it. – jmasterx Nov 13 '13 at 22:26
  • Memory management in modern objective c is handled by the ARC system, an explanation of which would be way too long for a comment on SO. I suggest researching property declarations in objective c and Automatic Reference Counting (ARC). – Lance Nov 13 '13 at 22:28
0

This kind of thing usually works for me

NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:2.0]; // 2 sec from now
NSTimer *self.timer = [[NSTimer alloc] initWithFireDate:fireDate interval:5 target:self selector:@selector(timerDidTick) userInfo:nil repeats:YES]; // fire 5 sec apart
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:self.timer forMode:NSDefaultRunLoopMode];
Wilmar
  • 1,451
  • 13
  • 17