简体   繁体   English

延迟后执行选择器只调用一次

[英]perform selector after delay only called once

I have an app in which i need to call an instance method after every 1 or 2 seconds. 我有一个应用程序,我需要在每1或2秒后调用一个实例方法。 Now if i place 现在,如果我放置

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

in viewDidLoad: or viewWillAppear: , the method getMatchListWS is called only once as the view appears or loads. 在viewDidLoad:或viewWillAppear:中,方法getMatchListWS仅在视图出现或加载时被调用一次。 But i need to call the method continuously even when the user is on that view without the view being disappeared or unload. 但是我需要连续调用该方法,即使用户在该视图上而视图没有消失或卸载。 So, what is the correct place or delegate method in which i can add performSelector method so that it is called every second without having to unload the view again and again. 那么,我可以添加performSelector方法的正确位置或委托方法是什么,以便每秒调用它而不必一次又一次地卸载视图。 Do i need to do something in background or on main thread.? 我是否需要在后台或主线程中执行某些操作。 Thanks in advance!! 提前致谢!!

It would be like this: 它会是这样的:

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

Put it in your viewDidLoad , so you don't have problems with multiple events being fired. 将它放在viewDidLoad ,这样就不会遇到触发多个事件的问题。 It can happen if you put it on viewWillAppear or viewDidAppear , and you are pushing or showing a modalViewController. 如果将它放在viewWillAppearviewDidAppear ,并且您正在推送或显示modalViewController,则会发生这种情况。

Jacky Boy's answer will get your job done. Jacky Boy的回答将完成你的工作。 An alternate solution(if you're keen on using performSelector method) would be to add the same line in your method definition like so 另一种解决方案(如果您热衷于使用performSelector方法)将在方法定义中添加相同的行,如此

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

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

Note: You should still call the method once when the view loads. 注意:在加载视图时,您仍应该调用该方法一次。

You are just keeping a delay in your call. 你只是在延迟通话。 What that will do, is to call your method after a delay of 1 second. 那会做的是在延迟1秒后调用你的方法。 What you need to do is to set the timer to call your method repeatedly after a particular time interval. 您需要做的是将计时器设置为在特定时间间隔后重复调用您的方法。

//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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM