在Swift中,如何使用GCD在主執行緒上呼叫帶引數的方法?


在Swift中,你可以輕鬆地透過GCD在主執行緒上呼叫帶引數的方法。你可以使用`DispatchQueue.main.async`方法在主執行緒上執行方法。讓我們學習如何在Swift中實現這一點。此外,你還可以使用`DispatchQueue.main.asyncAfter`方法在延遲後呼叫帶引數的方法。

Grand Central Dispatch (GCD)

在iOS、macOS和其他Apple作業系統中,Grand Central Dispatch (GCD)是一個低級別的C API,它提供對併發程序的有效、系統範圍的控制。它構建在更低級別的排程佇列和執行緒管理原語之上。

排程佇列是GCD用來組織任務的工具。排程佇列是一種資料結構,用於儲存必須執行的任務列表。工作執行緒可以執行已新增到佇列中的任務。

在主佇列上執行任務

在這個例子中,我們將實現一個帶引數的方法。之後,我們將看到如何使用`DispatchQueue.main.async`方法呼叫該方法。這是一個例子。

這是非同步地在主佇列上執行任務的語法。

DispatchQueue.main.async {
   // write the code here to update the user interface.
}

如何在主執行緒上呼叫方法?

示例

// defines a method that takes a parameter
func greeting(fullName: String) {
   let message = "Good morning, \(fullName)"
   print(message)
}

// Call the method on the main thread using GCD
DispatchQueue.main.async {
   self.greeting(fullName: "Alex Murphy")
}

輸出

Good morning, Alex Murphy

在這個例子中,我們定義了一個名為greeting的方法,它帶有一個引數:型別為String的fullName。然後,我們透過將方法呼叫包裝在`DispatchQueue.main.async`中,使用GCD在主執行緒上呼叫此方法。引數作為引數傳遞給方法呼叫。

如何使用閉包呼叫帶引數的方法?

在這個例子中,我們將建立一個方法來查詢陣列中的最大值,該方法使用閉包返回最大值。這是一個例子。

示例

import UIKit
func findMax(_ array: [Int], performMax: @escaping ((Int) -> Void)) {
   var maxValue: Int = 0
   for value in array {
      if value > maxValue {
         maxValue = value
      }
   }   
   performMax(maxValue)
}
let numberArray = [23, 34, 43, 68, 21, 9]
DispatchQueue.main.async {
   findMax(numberArray) { max in
      print("Max value: \(max)")
   }
}

輸出

Max value: 68

如何在延遲後在主執行緒上呼叫帶引數的方法?

在這個例子中,我們將建立一個方法來查詢陣列中的最大值,該方法使用閉包返回最大值。我們將在主執行緒上延遲呼叫此方法。這是一個例子。

示例

import UIKit
func findMax(_ array: [Int], performMax: @escaping ((Int) -> Void)) {
   var maxValue: Int = 0
   for value in array {
      if value > maxValue {
         maxValue = value
      }
   }    
   performMax(maxValue)
}
let numberArray = [23, 34, 43, 68, 21, 9]
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
   findMax(numberArray) { max in
      print("Max value: \(max)")
   }
}

輸出

Max value: 68

結論

總之,要在Swift中使用GCD在主執行緒上呼叫帶引數的方法,你可以將方法呼叫包裝在一個傳遞給`DispatchQueue.main.async`的塊中。這將排程該塊在主執行緒上非同步執行,允許你執行UI更新或其他必須在主執行緒上執行的任務。記住,以通常的方式將方法引數作為引數傳遞給塊中的方法呼叫。

更新於:2023年4月24日

659 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告