Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer doesn't call method

I'm really frustrated now, googled the whole internet, stumbled through SO and still didn't find a solution.

I'm trying to implement an NSTimer, but the method which I defined doesn't get called. (seconds are set correctly, checked it with breakpoints). Here is the code:

- (void) setTimerForAlarm:(Alarm *)alarm {
    NSTimeInterval seconds = [[alarm alarmDate] timeIntervalSinceNow];
    theTimer = [NSTimer timerWithTimeInterval:seconds 
                            target:self 
                          selector:@selector(showAlarm:)
                          userInfo:alarm repeats:NO];
}

- (void) showAlarm:(Alarm *)alarm {
    NSLog(@"Alarm: %@", [alarm alarmText]);
}

The object "theTimer" is deined with @property:

@interface FooAppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>  {
@private

    NSTimer *theTimer;

}

@property (nonatomic, retain) NSTimer *theTimer;

- (void) setTimerForAlarm:(Alarm *)alarm;
- (void) showAlarm:(Alarm *)alarm;

What am I doing wrong?

like image 308
tamasgal Avatar asked May 20 '11 15:05

tamasgal


2 Answers

timerWithTimeInterval simply creates a timer, but doesn't add it to any run loops for execution. Try

self.theTimer = [NSTimer scheduledTimerWithTimeInterval:seconds 
                        target:self 
                      selector:@selector(showAlarm:)
                      userInfo:alarm repeats:NO];

instead.

like image 114
JimDusseau Avatar answered Sep 22 '22 16:09

JimDusseau


Also don't forget to check if

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds 
                                     target:(id)target 
                                   selector:(SEL)aSelector 
                                   userInfo:(id)userInfo 
                                    repeats:(BOOL)repeats 

is called in the main thread.

like image 31
Petr Syrov Avatar answered Sep 20 '22 16:09

Petr Syrov