2

I've created a simple button game that gives the user a point with every tap of the button. The button randomly appears on screen every 1.5 seconds. I want the game to end after 30 seconds or after 20 random button pop ups. I've been using the code below to have the button randomly pop-up on the screen:

timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self
         selector:@selector(moveButton:) 
         userInfo:nil 
         repeats:YES];

I've declared the timer in the header file:

NSTimer *timer;
@property (nonatomic, retain) NSTimer *timer;

I've read Apple Docs on Using Timers but fail to fully understand it. I thought maybe I could use:

- (void)countedTimerFireMethod:(NSTimer *)timer{
  count ++;
  if(count > 20){
     [self.timer invalidate];
     self.timer = nil;

But it does not work properly. What am I doing wrong? I'm new to objective-C so I'm not that familiar with how things work.

Brian
  • 2,494
  • 1
  • 16
  • 21

2 Answers2

4

The problem is on your timer method you are passing moveButton method but in below method where you are stopping the timer that method name is different so try this:-

  self.timer = [NSTimer     
  scheduledTimerWithTimeInterval: 1.5 target:self
     selector:@selector(moveButton:) 
     userInfo:nil 
     repeats:YES];

//just change the method name below

 - (void)moveButton:(NSTimer *)timer{
  count ++;
  if(count > 20){
    [self.timer invalidate];
    self.timer = nil;}
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
  • To be clear, the issue is that the selector passed to the schedule method is not the same as the method name below. – Jesse Rusak Oct 26 '13 at 17:47
  • THANK YOU VERY MUCH!!! While this did not directly answer my question, it did lead my to the answer. – Brian Oct 26 '13 at 23:12
0

If you are using new version of Xcode then you don not need to declare

NSTimer *timer;

and when scheduling a timer you can use

self.timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self
         selector:@selector(moveButton:) 
         userInfo:nil 
         repeats:YES]

instead of

timer = [NSTimer scheduledTimerWithTimeInterval: 1.5 target:self
         selector:@selector(moveButton:) 
         userInfo:nil 
         repeats:YES]

You are using correct method to stop the timer i.e invalidate

You can also refer the link for more clarification.

Please let me know if you solve this problem through the above code.

Community
  • 1
  • 1
creative_rd
  • 695
  • 6
  • 13