André André - 6 months ago 20
Objective-C Question

NSTimer initialized with fireDate does not fire

I am trying to use an

NSTimer
to call a method, but it doesn`t work.
I need this method to be run once, at a specific date and time, which the user sets on a calendar.

I have this code in my
viewDidLoad
method:

NSDateComponents *comps = [[NSDateComponents alloc] init];

[comps setDay:24];
[comps setMonth:10];
[comps setYear:2011];

[comps setHour:23];
[comps setMinute:11];
[comps setSecond:0];


NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
schedulerTimer=[[NSTimer alloc] initWithFireDate:date interval:0 target:self selector:@selector(recordByScheduler:) userInfo:nil repeats:false];


But this code does nothing. Probably I misunderstood
NSCalendar
. What should I be doing here? And a second question: is
NSTimer
fired when the application is running in the background?

Answer

You need to schedule the timer in the runloop.

[[NSRunLoop currentRunLoop] addTimer:schedulerTimer forMode:NSDefaultRunLoopMode];

Or similar, depending on situation.

Response to question edit:

No NSTimer is not fired when your application is in the background.

Comments