40pro
40pro

Reputation: 1281

iOS NSTimer not calling selector - not firing

I have:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self setNeedsStatusBarAppearanceUpdate];
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(setCurrentTime:)  userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [timer fire];

}
-(void)setCurrentTime{
    NSLog(@"TEST");
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDate *currentDate = [[NSDate alloc] init];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        [currentTime setText:[dateFormatter stringFromDate:currentDate]];
    });
}

But nothing get called.

Upvotes: 1

Views: 5868

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89509

You're calling the wrong selector. Your "setCurrentTime" implementation doesn't take any parameter (e.g. to be properly messaged or called, you should use "selector:@selector(setCurrentTime)".

Now, if you look at Apple's documentation for [NSTimer scheduledTimerWitTimeInterval: target: selector: userInfo: repeats:], Apple says your method should have this signature:

- (void)setCurrentTime: (NSTimer *) timer

Which means your function would look something like this:

-(void)setCurrentTime: (NSTimer *) timer
{
    NSLog(@"TEST");
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDate *currentDate = [[NSDate alloc] init];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        [currentTime setText:[dateFormatter stringFromDate:currentDate]];
    });
}

and be called like this:

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.25 
                   target:self 
                 selector:@selector(setCurrentTime:)  
                 userInfo:nil 
                  repeats:YES];

Upvotes: 7

Related Questions