【问题标题】:perform selector after delay only called once延迟后执行选择器只调用一次
【发布时间】:2013-04-22 08:15:51
【问题描述】:

我有一个应用程序,我需要每隔 1 或 2 秒调用一次实例方法。现在如果我放置

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

在 viewDidLoad: 或 viewWillAppear: 中,getMatchListWS 方法仅在视图出现或加载时调用一次。但是即使用户在该视图上而视图没有消失或卸载,我也需要连续调用该方法。那么,什么是正确的位置或委托方法,我可以在其中添加 performSelector 方法,以便每秒调用一次,而不必一次又一次地卸载视图。我需要在后台或主线程上做些什么吗?提前致谢!!

【问题讨论】:

    标签: ios objective-c xcode viewdidload performselector


    【解决方案1】:

    应该是这样的:

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

    将它放在您的viewDidLoad 中,这样您就不会遇到多个事件被触发的问题。如果你把它放在viewWillAppearviewDidAppear 上,并且你正在推送或显示一个modalViewController,就会发生这种情况。

    【讨论】:

    • 如果你想让它只重复一次,那就是repeats:NO。来自文档:repeats If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
    【解决方案2】:

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

    -(void) getMatchListWS {
    //Get Match List here
    
    [self performSelector:@selector(getMatchListWS) withObject:nil afterDelay:1.0];
    }
    

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

    【讨论】:

    • 必须这样声明吗? -(void)getMatchListWS:(NSTimer *)dt{} 并以这种方式调用? [self performSelector:@selector(getMatchListWS:) withObject:nil afterDelay:1.0];
    【解决方案3】:

    您只是在延迟通话。这样做是在延迟 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];
    

    【讨论】:

      猜你喜欢
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      相关资源
      最近更新 更多