1. 程式人生 > >[Xcode10 實際操作]八、網路與多執行緒-(19)使用RunLoop使PerformSelector方法延遲動作的執行

[Xcode10 實際操作]八、網路與多執行緒-(19)使用RunLoop使PerformSelector方法延遲動作的執行

本文將演示使用RunLoop使PerformSelector方法延遲動作的執行。

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     //新增一個布林屬性,用來標識載入狀態
 6     var stillLoading = true
 7     
 8     override func viewDidLoad() {
 9         super.viewDidLoad()
10         //
Do any additional setup after loading the view, typically from a nib. 11 12 //建立一個位置在(100,100),尺寸為(100,30)的顯示區域。 13 let rect = CGRect(x: 100, y: 100, width: 100, height: 30) 14 //初始化一個標籤物件,設定標籤物件的位置和尺寸資訊 15 let label = UILabel(frame: rect) 16 //設定標籤物件的顯示內容 17 label.text = "
Waiting" 18 //給標籤物件設定標識值,一邊將來通過標識值,來呼叫標籤物件。 19 label.tag = 1 20 //將標籤物件,新增到當前檢視控制器的根檢視 21 self.view.addSubview(label) 22 23 //執行一個方法,並設定延遲執行為0秒,即立即執行該方法 24 self.perform(#selector(ViewController.threadEvent), with: nil, afterDelay: 0.0) 25 }
26 27 //新增一個方法,用來響應定時事件 28 @objc func threadEvent() 29 { 30 //執行一個方法,並設定延遲執行為2秒,即等待2秒後,執行該方法 31 self.perform(#selector(ViewController.workInBackground), with: nil, afterDelay: 2.0) 32 33 //新增一條while語句,這條語句將使方法一直處於執行狀態, 34 while stillLoading 35 { 36 //直到布林變數值為假,才會跳出當前迴圈,以此實現執行緒等待阻塞 37 RunLoop.current.run(mode:.default, before: Date.distantFuture) 38 } 39 40 //當程式跳出當前的迴圈語句時,隱藏標籤物件 41 self.view.viewWithTag(1)?.isHidden = true 42 } 43 44 //新增一個方法,用來響應定時事件 45 @objc func workInBackground() 46 { 47 //將變數的值設為否,以清除執行緒的阻塞 48 print(">>>>>>>>>>>>>>>>>>>") 49 stillLoading = false 50 } 51 52 override func didReceiveMemoryWarning() { 53 super.didReceiveMemoryWarning() 54 // Dispose of any resources that can be recreated. 55 } 56 }