[英]NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats doesn't invoke the method
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 谢谢
It was a thread issue. 这是一个线程问题。 I've fixed with:
我已经解决了:
dispatch_async(dispatch_get_main_queue(), ^{
// Timer here
});
You don't need an NSTimer for a task of this sort. 您不需要NSTimer即可完成此类任务。 To hide your view object after a specific period of time on main thread you can use a gcd method dispatch_after
要在特定时间段后在主线程上隐藏视图对象,可以使用gcd方法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 其中2.0是执行块之前将经过的秒数
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. 按下
btn
(一个UIButton
)并调用-(void)btnPressed
函数时,此代码运行良好。
-(void)btnPressed{
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(hideManual) userInfo:nil repeats:NO];
}
-(void)hideManual{
NSLog(@"Hi, I'm here!");
}
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];
in your code fragments it does not show when and where the NSTimer
is fired. 在您的代码片段中,它不会显示触发
NSTimer
时间和位置。
if you want to use the NSTimer
, you should fire the timer after the init, like this: 如果要使用
NSTimer
,则应在初始化之后触发计时器,如下所示:
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
. 在这种情况下,它看起来比使用
NSTimer
容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.