问题描述
在我的项目中实现它之前,我已经用计时器创建了一个测试应用程序。
这是我第一次使用计时器。
但问题是当我使用 [NSTimer timerWithTimeInterval:target:selector:userInfo:repeats:];
实现计时器时,它无效。
这是我的代码,
接口:
I've created a test application with timer before implementing it in my project.It was the first time I'm using timer.But the issue is when I implemented timer using [NSTimer timerWithTimeInterval: target: selector: userInfo: repeats: ];
, it is not working.Here is my code,Interface:
@interface uialertViewController : UIViewController
{
NSTimer *timer;
}
-(void)displayAlert;
-(void)hideandview;
@end
实施:
@implementation uialertViewController
- (void)viewDidLoad {
[self displayAlert];
[super viewDidLoad];
}
-(void)displayAlert{
timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(hideandview) userInfo:nil repeats:NO];
alert = [[UIAlertView alloc] initWithTitle:@"testing" message:@"hi hi hi" delegate:nil cancelButtonTitle:@"continue" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
-(void)hideandview{
NSLog(@"triggered");
[alert dismissWithClickedButtonIndex:0 animated:YES];
[alert release];
[self displayAlert];
}
@end
然后我改变了 [NSTimer timerWithTimeInterval:target:selector:userInfo:repeats:];
with [NSTimer scheduledTimerWithTimeInterval:target :selector:userInfo:重复:];
,它正在运行。 timerWithTimeInterval:
的问题是什么?在我的第一次实施中,我是否正在做什么?在此先感谢。
Then I Changed [NSTimer timerWithTimeInterval: target: selector: userInfo: repeats: ];
with [NSTimer scheduledTimerWithTimeInterval: target: selector:userInfo: repeats: ];
, It is working. What was the issue with timerWithTimeInterval:
? Am I mising anything in my first implementation ? Thanks in advance.
推荐答案
scheduledTimerWithTimeInterval:invocation:repeats:
和 scheduledTimerWithTimeInterval:target:selector:userInfo:重复:
创建自动添加到 NSRunLoop
的计时器,这意味着你不要必须自己添加它们。将它们添加到 NSRunLoop
是导致它们触发的原因。
scheduledTimerWithTimeInterval:invocation:repeats:
and scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
create timers that get automatically added to an NSRunLoop
, meaning that you don't have to add them yourself. Having them added to an NSRunLoop
is what causes them to fire.
使用 timerWithTimeInterval:调用:重复:
和 timerWithTimeInterval:target:selector:userInfo:重复:
,你必须手动将定时器添加到运行循环中,使用代码像这样:
With timerWithTimeInterval:invocation:repeats:
and timerWithTimeInterval:target:selector:userInfo:repeats:
, you have to add the timer to a run loop manually, with code like this:
[[NSRunLoop mainRunLoop] addTimer:repeatingTimer forMode:NSDefaultRunLoopMode];
此处的其他答案建议您需要致电 fire
你自己。你不这样做 - 只要计时器被置于一个运行循环就会被调用。
Other answers on here suggest that you need to call fire
yourself. You don't - it will be called as soon as the timer has been put on a run loop.
这篇关于NSTimer timerWithTimeInterval:不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!