Custom RunLoop Mode - objective-c

What am I doing wrong here? What am I missing?
- (void)scheduleTimer
{
NSTimer *timer = [NSTimer timerWithTimeInterval:0.15
target:self
selector:#selector(wtf:)
userInfo:nil
repeats:NO];
// This works fine
// [[NSRunLoop currentRunLoop] addTimer:timer
// forMode:NSDefaultRunLoopMode];
// This doesn't work at all - how come?
[[NSRunLoop currentRunLoop] addTimer:timer
forMode:#"MyCustomRunLoopMode"];
}
- (void)wtf:(NSTimer *)aTimer
{
NSLog(#"wtf");
}
The documentation for NSRunLoop seems to indicate one can create custom runloop modes. Am I missing something?
(This is on the main thread of a standard GUI application in Mac OS X)
Update: Notice that I mentioned this was on the main thread of a standard application. Therefore, I'm not running the runloop myself. It's all being handled by NSApplication.

Are you running the runloop for that mode? Just adding a timer won't do anything if the runloop never runs in that mode.

Could it be that the currentRunLoop only runs in common modes?
You should also try:
- (BOOL)runMode:(NSString *)mode beforeDate:(NSDate *)limitDate
and check things out with:
- (NSString *)currentMode
--Tom

Related

NStimer I want to call methos in background

I want to make calls in background for every 3 min, so I am using Twilio for that. I am able to make calls for every 3 in foreground, but when I built app on iPhone device in background it is not working. After some time fb session is getting logout..
UIApplication *app1 = [UIApplication sharedApplication];
//create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask1 = [app1 beginBackgroundTaskWithExpirationHandler:^{
[app1 endBackgroundTask:bgTask1];
bgTask1 = UIBackgroundTaskInvalid;
}];
//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//run function methodRunAfterBackground
timerForPhone = [NSTimer scheduledTimerWithTimeInterval:[string integerValue] target:self selector:#selector(methodForMakingCall) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timerForPhone forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
After you put the app into background you don't have much control on it. OS can kill it according to resource needs. Unlike Android, you need to wake your app in order to do some logic. There are some workarounds like using location manager's significant change mechanism but still there is not a designated API for this. You need to keep this in mind whenever you are doing some background logic on iOS.

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.
I was having a similar problem, and it had a different root cause, related to the run loop. It's worth noting that when you schedule the Timer with the code:
updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01428 target:self selector:#selector(GameUpdate) userInfo:nil repeats:YES];
The timer will get scheduled with the current thread's runLoop. In your case, because you make this call within the viewDidLoad, it is the main thread, so you are are good to go.
However, if you schedule your timer with a thread other than the main thread, it will get scheduled on the runLoop for that thread, and not main. Which is fine, but on auxiliary threads, you are responsible for creating and starting the initial run loop, so if you haven't done that - your callback will never get called.
The solution is to either start the runLoop for your auxiliary thread, or to dispatch your timer start onto the main thread.
to dispatch:
dispatch_async(dispatch_get_main_queue(), ^{
updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01428 target:self selector:#selector(GameUpdate) userInfo:nil repeats:YES];
});
To start a runloop:
After creating a thread using your API of choice, call CFRunLoopGetCurrent() to allocate an initial run loop for that thread. Any future calls to CFRunLoopGetCurrent will return the same run loop.
CFRunLoopGetCurrent();
updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01428 target:self selector:#selector(GameUpdate) userInfo:nil repeats:YES];
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.
Just in case anyone stumbles across this, I want to point out that this:
[[NSString alloc] initWithFormat:#"Frame: %d", i];
Needs memory management.
Safely replace with:
[NSString stringWithFormat:#"Frame: %d", i];
for the same effect but no need for memory management.
P.S. At time of writing I cannot comment on the original post, so I've added this as an answer.
EDIT: As adam waite pointed out below, this isn't really relevant anymore with the widespread usage of ARC.
I have had a little bit different issue with NSTimer - scheduled method call was ignored during UITableView scrolling.
Timer had been started from main thread. Adding timer explicitly to main run loop resolved the problem.
[[NSRunLoop mainRunLoop] addTimer:playbackTimer forMode:NSRunLoopCommonModes];
Solution found here https://stackoverflow.com/a/2716605/1994889
UPD: CADisplayLink fits much better for updating UI.
According official documentation, CADisplayLink is a:
Class representing a timer bound to the display vsync.
And can be easily implemented like:
playbackTimer = [CADisplayLink displayLinkWithTarget:self selector:#selector(updateUI)];
[playbackTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
and removed like
if (playbackTimer) {
[playbackTimer removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
playbackTimer = nil;
}

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 + Modal Problem

I'm trying to run a timer while running an NSWindow as modal, but unfortunately it doesn't work at all. The log is called, the window appears and turns modal, but the timer is never called - why? Am I missing something?
NSLog(#"Checking...");
[[NSApplication sharedApplication] runModalForWindow:_Window];
_checkTimer = [NSTimer timerWithTimeInterval:1 target:self selector:#selector(check:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_checkTimer
forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer: _checkTimer
forMode:NSModalPanelRunLoopMode];
If you need for some reasons to add timer after starting modal session - so just add timer to run loop mode: NSModalPanelRunLoopMode
[[NSRunLoop currentRunLoop] addTimer:theTimer
forMode:NSModalPanelRunLoopMode];
Try doing your timer/runloop stuff before starting the modal session.