2013-04-22 57 views
3

我有一个应用程序,我需要在每1或2秒后调用实例方法。现在,如果我把在延迟后执行选择器只调用一次

[self performSelector:@selector(getMatchListWS) withObject:nil afterDelay:1.0]; 
在viewDidLoad中

:或viewWillAppear中:,该方法getMatchListWS称为视图出现或只加载一次。但即使当用户在视图中时,我也需要不断调用该方法,而视图不会消失或卸载。那么,我可以添加performSelector方法的正确位置或委托方法是什么,以便每秒调用一次,而无需一次又一次卸载视图。我是否需要在后台或主线程中执行某些操作?提前致谢!!

回答

11

这将是这样的:

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getMatchListWS:) userInfo:nil repeats:YES]; 

把它放在你viewDidLoad,所以你不要有被解雇的多个事件的问题。如果将它放在viewWillAppearviewDidAppear上,并且您正在推送或显示modalViewController,则可能会发生这种情况。

+4

如果你想它**只重复一次**,它是**重复:否**。从文档:'重复 如果是,计时器会重复计划自己,直到无效。如果否,计时器在火灾后将失效。“ – Peres 2013-04-22 08:20:51

7

Jacky Boy的回答将完成您的工作。另一种解决方案(如果你是热衷于使用performSelector法)是添加在同一行中的方法定义,像这样

-(void) getMatchListWS { 
//Get Match List here 

[self performSelector:@selector(getMatchListWS) withObject:nil afterDelay:1.0]; 
} 

注意:您仍然应该调用该方法,一旦视图加载时。

+0

必须以这种方式声明? - (void)getMatchListWS:(NSTimer *)dt {}并用这种方式调用? [self performSelector:@selector(getMatchListWS :) withObject:nil afterDelay:1.0]; – 2015-05-22 07:46:41

1

你只是在延迟你的电话。那会做什么,是延迟1秒后调用你的方法。你需要做的是设置定时器在特定的时间间隔后重复调用你的方法。

//create an instance of NSTimer class 
NSTimer *timer; 

//set the timer to perform selector (getMatchListWS:) repeatedly 
timer= [NSTimer timerWithTimeInterval:1.0 
             target:self 
             selector:@selector(getMatchListWS:) 
             userInfo:nil 
             repeats:YES];