在Xamarin.iOS中添加计时器的位置?

nic*_*cks 5 xamarin.ios ios xamarin

当我显示页面时,我需要每隔一分钟发出一次请求来更新显示的表格中的数据.我不知道在哪里添加这个定时器逻辑,因为所有控制器生命周期方法应该在适当的时间结束 - 我猜?

我应该把计时器放在哪里?

Dav*_*iha 3

由于您说您需要在显示页面后每隔一分钟发出一次请求,所以好的解决方案是在ViewWillAppear()方法中启动计时器并停止它ViewWillDisappear()- 当 ViewController 在前台可见时它将运行。解除绑定OnTimedEvent对于避免内存泄漏很重要。

这是您所需要的还是您有更具体的要求?

示例代码:

class MyViewController : UIViewController
{
    public MyViewController(IntPtr handle)
        : base(handle)
    {
    }

    private Timer timer;
    private bool timerEventBinded;

    public override void ViewWillAppear(bool animated)
    {
         base.ViewWillAppear(animated);
         if (timer == null)
         {
            timer = new Timer();
            timer.Enabled = true;
            timer.Interval = 60000;
         }

         if (!timerEventBinded)
         {
            timer.Elapsed += OnTimedEvent;
            timerEventBinded = true;
         }

         timer.Start();
    }

    public override void ViewWillDisappear(bool animated)
    {
        if (timer != null)
        {
           timer.Stop();
           if (timerEventBinded)
           {
              timer.Elapsed -= OnTimedEvent;
              timerEventBinded = false;
           }
           timer = null;
        }

        base.ViewWillDisappear(animated);
    }

    private void OnTimedEvent(Object src, ElapsedEventArgs e)
    {
        //do your stuff
    }
}
Run Code Online (Sandbox Code Playgroud)