NSTimer stop when app is hide? - objective-c

I just want to know why a NSTimer is stoping when the application is hidden or "Hide other" in an other application ?
how can I remedy this ?
Thanks

Maybe your timer is getting garbage collected or otherwise freed perhaps by the autorelease pool, and hence does not fire anymore.
Try doing this:
- (IBAction)recordCam1:(id)sender {
myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(recordFile1:) userInfo:Nil repeats:YES];
[myTimer retain];
}
where myTimer is an instance variable in your class. See if that produces a different behaviour. If so, then you know the problem is to do with memory management.

Related

Xcode - NSTimer firing at random intervals? No consistency

So I am using NSTimer to run a function every minute, it fires at the correct time for the first 3 or so attempts and then it suddenly starts firing every second. I have no idea why this is happening? Would anyone be able to let me know as to why NSTimer is firing inconsistently?
Here is the line where I have declared my timer.
[NSTimer scheduledTimerWithTimeInterval:60.0f target:self selector:#selector(checkForLocation) userInfo:nil repeats:YES];
It is worth noting that I have NSTimer declared inside of viewDidAppear.
Any help is appreciated,
Thank you.
Try to create a instance for NSTimer by declaring a property. Write a function which will initialize the timer and don’t forget to invalidate it before re-intializing it. Call initializeMyTimer in your -viewDidAppear.
-(void) initializeMyTimer
{
if(myTimer)
{
[myTimer invalidate];
myTimer = nil;
}
myTimer = [NSTimer scheduledTimerWithTimeInterval:60.0f
target:self
selector:#selector(checkForLocation)
userInfo:nil
repeats:YES];
}

iOS5 ARC is it safe to schedule NSTimers from background selectors?

I'm trying to debug my application.
I've been using some NSTimer instances in my non-arc code like this (from the main thread):
[NSTimer scheduledTimerWithTimeInterval:5 target:musicPlayer selector:#selector(playPause:) userInfo:nil repeats:NO];
This works fine if I assign this code to a button and click a button. The timer fires.
I've also tried:
if( self.deliveryTimer == nil)
{
self.deliveryTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(playPause:) userInfo:nil repeats:NO];
}
-(void)playPause:(NSTimer*)timer
{
[deliveryTimer invalidate];
deliveryTimer = nil;
//more code here
}
I would expect the timer to execute, hit the play/pause method below, then turn to nil, so I can reset the timer later. The reason why I'm checking for nil is because I have 3 different code paths that may set the timer. Each one has an NSLog statement indicating that the timer has been scheduled.
My code runs, and I see that the timers are being scheduled, but they don't seem to fire in the course of normal app execution. I'm investigating why. Short term timers, using the same logic fire fine. It is when I let the app run for a while that I'm running into issues.
Could the NSTimers be reclaimed by ARC?
Does it matter if I set the timer from a performSelectorInBackground? As I was writing up this question, I noticed that some of my timers were created from a code path that is being called through:
[self performSelectorInBackground:#selector(notifyDelegateOfDataPoint:) withObject:data];
could the background selector be the reason why my timers do not fire/get reclaimed earlier?
Any help is appreciated, this bug has been bugging me for over 2 weeks!
Update: after changing the code to use the main thread for NSTimers, the timers fire correctly, causing the music to play:
[self performSelectorOnMainThread:#selector(deliverReminder:) withObject:nil waitUntilDone:NO];
-(void)deliverReminder:(id)sender{
[ NSTimer scheduledTimerWithTimeInterval:10 target:reminderDeliverySystem selector:#selector(playAfterDelay:) userInfo:nil repeats:NO];
[self postMessageWithTitle:nil message:#"Deliver Reminder Called" action:kNoContextAction];
}
-(void)playAfterDelay:(id)sender
{
int reminderDelay = reminder.delayValue.intValue;
[playTimers addObject:[NSTimer scheduledTimerWithTimeInterval:reminderDelay target:self selector:#selector(appMusicPlayerPlay:) userInfo:nil repeats:NO]];
}
Here I have a whole bunch of timers, which is because I don't know how to pass a primitive to a target with a selector.
An NSTimer requires a run loop to be running in that background thread for it to keep firing. The main thread already has an active run loop, which is why your timers work fine when executed on it.
If you want to use your timers within a background thread, you can do something like the following:
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
self.deliveryTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(playPause:) userInfo:nil repeats:NO];
[runLoop run];
What was probably happening with your short duration timers firing, but the longer ones not, was that they were firing while the thread was still active, but without a run loop to keep it going, were failing after the thread reached the end of its execution.
I don't believe this is ARC-related, although there may be something there you'll have to watch for, because the NSRunLoop holds on to a timer that is attached to it. Following standard procedure with NSTimers should avoid ARC problems.

NSTimer not firing

I have an NSTimer that I init with this code:
testTimer = [[NSTimer alloc] initWithFireDate:[new objectAtIndex:0] interval:0.0 target:self selector:#selector(works:) userInfo:nil repeats:NO];
[new objectAtIndex:0] is an NSDate in the past.
When I start up the app, the timer is getting created, with a fireDate of immediately (since the date is in the past), however it never calls my works method. (-(void)works:(id)sender
)
Anybody know why this is happening?
You will have to add it to the current run loop if you use initWith.. method to create the timer object.
NSRunLoop * theRunLoop = [NSRunLoop currentRunLoop];
[theRunLoop addTimer:testTimer forMode:NSDefaultRunLoopMode];
Or if you would like it set up for you, use the scheduled... methods to create your timer.
I just recently had an issue with NSTimer. In my case I didn't realize that the method scheduledTimerWithTimeInterval is not multi thread safe. Once I moved the timer to the main thread it started working.
I think I had the same problem as Dobler, but my solution was different.
The problem was that the timer was being created and scheduled in a GCD thread in a block within a
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{})
call (actually nested deep, so it wasn't obvious that this was the case).
Using NSTimer's scheduledTimerWithTimeInterval:... placed the timer into an invalid run loop.
The fix was to change to
timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:#selector(...) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

NSTimer crash with EXC_BAD_ACCESS in shared class

I have an NSTimer running in a shared class. + (GlobalClass *)sharedInstance;
Basically it runs once, and the second time it runs, it just killed the whole app.
This is how I'm doing the NSTimer
myTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:#selector(moveMe)
userInfo:nil
repeats:YES];
method moveMe is just an empty method for now. So it shouldn't be something that's happening within moveMe.
Has anyone experienced this?
It looks like you're missing the colon in your selector name. The selector for NSTimer takes an NSTimer as an argument. Your code that creates the timer should look like this:
myTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:#selector(moveMe:)
userInfo:nil
repeats:NO];
Note the colon after moveMe. Your method should then look something like this:
- (void)moveMe:(NSTimer *)aTimer {
// Code
}

Timer invalidate

What is the meaning of this statement given?
NSTimer *timer ,[timer invalidate]
It's an objective C timer statement that cancels a running timer.
Normally it would be expressed as:
NSTimer* myTimer = [NSTimer timerWithTimeInterval:1.0 target:self
selector:#selector(calculateTLE) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:myTimer forMode: NSDefaultRunLoopMode];
..
[myTimer invalidate];
It looks as though you're creating an instance of NSTimer without defining it, and then in the same line for whatever reason stopping that same timer. Waste of memory allocation resources, unless you're planning to use the timer at a later time, in which case you should trigger the timer then.