NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats doesn't invoke the method

戏子无情 提交于 2019-12-21 11:55:30

问题


The timer never invokes the method. What am I doing wrong ? This is the code:

NSTimer *manualOverlayTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(hideManual) userInfo:nil repeats:NO];

method:

-(void)hideManual

thanks


回答1:


It was a thread issue. I've fixed with:

dispatch_async(dispatch_get_main_queue(), ^{
    // Timer here
});



回答2:


You don't need an NSTimer for a task of this sort. To hide your view object after a specific period of time on main thread you can use a gcd method dispatch_after

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 2.0), dispatch_get_main_queue(), ^(void){
    // Your code
  });

where 2.0 is an amount of seconds that will pass before the block will get executed




回答3:


Just use this

[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(hideManual) userInfo:nil repeats:NO];

EDIT

This code work well when btn (an UIButton) pressed and -(void)btnPressed function called.

-(void)btnPressed{
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(hideManual) userInfo:nil repeats:NO];
}

-(void)hideManual{
    NSLog(@"Hi, I'm here!");
}



回答4:


try this :

NSTimer *manualOverlayTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                              target:self
                              selector:@selector(hideManual)
                              userInfo:nil
                              repeats:YES];

repeat:YES instead of [[NSRunLoop currentRunLoop] addTimer:manualOverlayTimer forMode:NSDefaultRunLoopMode];



回答5:


in your code fragments it does not show when and where the NSTimer is fired.

if you want to use the NSTimer, you should fire the timer after the init, like this:

NSTimer *_timer = [NSTimer scheduledTimerWithTimeInterval:2.f target:self selector:@selector(hideManual) userInfo:nil repeats:false];
[_timer fire];

but you can use the following line in your any method as well:

[self performSelector:@selector(hideManual) withObject:nil afterDelay:2.f];

it looks easier in this case than working with NSTimer.



来源:https://stackoverflow.com/questions/11501186/nstimer-scheduledtimerwithtimeintervaltargetselectoruserinforepeats-doesnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!