1. 程式人生 > >以+scheduledTimerWithTimeInterval...的方式觸發的timer,在滑動頁面上的列表時,timer會暫定回調,為什麽?如何解決?

以+scheduledTimerWithTimeInterval...的方式觸發的timer,在滑動頁面上的列表時,timer會暫定回調,為什麽?如何解決?

指定 val timer 運行模式 sch 發的 滑動頁面 循環 oop

  • 這裏強調一點:在主線程中以+scheduledTimerWithTimeInterval...的方式觸發的timer默認是運行在NSDefaultRunLoopMode模式下的,當滑動頁面上的列表時,進入了UITrackingRunLoopMode模式,這時候timer就會停止
  • 可以修改timer的運行模式為NSRunLoopCommonModes,這樣定時器就可以一直運行了

  • 以下是我的筆記補充:

    • 子線程中通過scheduledTimerWithTimeInterval:...方法來構建NSTimer
      • 方法內部已經創建NSTimer對象,並加入到RunLoop中,運行模式為NSDefaultRunLoopMode
      • 由於Mode有timer對象,所以RunLoop就開始監聽定時器事件了,從而開始進入運行循環
      • 這個方法僅僅是創建RunLoop對象,並不會主動啟動RunLoop,需要再調用run方法來啟動
    • 如果在主線程中通過scheduledTimerWithTimeInterval:...方法來構建NSTimer,就不需要主動啟動RunLoop對象,因為主線程的RunLoop對象在程序運行起來就已經被啟動了

      // userInfo參數:用來給NSTimer的userInfo屬性賦值,userInfo是只讀的,只能在構建NSTimer對象時賦值
      [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(run:) userInfo:@"ya了個hoo" repeats:YES];
      
      // scheduledTimer...方法創建出來NSTimer雖然已經指定了默認模式,但是【允許你修改模式】
      [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
      
      // 【僅在子線程】需要手動啟動RunLoop對象,進入運行循環
      [[NSRunLoop currentRunLoop] run];

以+scheduledTimerWithTimeInterval...的方式觸發的timer,在滑動頁面上的列表時,timer會暫定回調,為什麽?如何解決?