Search code examples
objective-cioscocoa-touchnstimer

NSTimer's action method is not being called


I have the following code to create an NSTimer which should update a label each time it fires:

.h file

@interface Game : UIViewController
{
    NSTimer *updateTimer;

    UILabel *testLabel;
    int i;
}
-(void)GameUpdate;

@end

.m file

@implementation Game

-(void)GameUpdate
{
    i++;
    NSString *textToDisplay = [[NSString alloc] initWithFormat:@"Frame: %d", i];
    [testLabel setText:textToDisplay];
    NSLog(@"Game Updated");
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
    updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01428 target:self selector:@selector(GameUpdate) userInfo:nil repeats:YES];
}

//other methods (viewDidUnload, init method, etc.)

@end

When I run it, a label appears in the top that says "0" but does not change. It makes me believe I missed something in how the NSTimer is to be setup. What did I miss?

I used breakpoints and (as you can see) logging to see if the method is actually running, rather than some other error.


Solution

  • Your callback must have this signature:

    -(void)GameUpdate:(NSTimer *)timer
    

    This is explicitly in the docs. And the @selector() reference when you setup the timer should be @selector(GameUpdate:) (notice the trailing :).

    Try that.