Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer not firing the selector

Tags:

ios

nstimer

In ios5.0 with ARC, in my rootviewcontroller I call a method in a security manager object that is held by the app delegate. In that method I setup the timer as below

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self 
                                       selector:@selector(updateModel:) userInfo:str repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; 

However, this never fires the selector ie. updateModel: never gets called. What may be wrong? Is there another more efficient way I can do this without using NStimer?

like image 769
inforeqd Avatar asked Mar 29 '12 02:03

inforeqd


3 Answers

Could also be a threading problem:

if

[NSThread isMainThread]

is false then start the timer like this:

dispatch_async(dispatch_get_main_queue(), ^{
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
    })
like image 65
tmanthey Avatar answered Oct 23 '22 02:10

tmanthey


You seem to be a bit mixed up with your timer variable.

You initialize a new timer but you aren't actually using it. Do you want to use the timer you initialized or do you want to you ApplicationDelegate.timer?

Here are the two possible solutions.

Option One (assuming that you have a class instance titled ApplicationDelegate and that it has a timer property):

ApplicationDelegate.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(updateModel:) userInfo:str repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:ApplicationDelegate.timer forMode:NSRunLoopCommonModes];

Option Two:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(updateModel:) userInfo:str repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
like image 34
sosborn Avatar answered Oct 23 '22 04:10

sosborn


I catch the same issue and I fire timer in main queue to solve it:

[NSURLConnection sendAsynchronousRequest:request queue:_operationQueue
    completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
         [self loopUpUpdateStart];
}];

-(void)loopUpUpdateStart{
    dispatch_async(dispatch_get_main_queue(), ^{

        _loopTimerForUpRevision = 
          NSTimer scheduledTimerWithTimeInterval: kNetworkLoopIntervalUpRev
                                          target: self
                                        selector: @selector(myCoolMethod)
                                        userInfo: nil
                                         repeats: YES];
        TRACE(@"Start Up updates");
    });
}
like image 8
WINSergey Avatar answered Oct 23 '22 02:10

WINSergey