2016-09-18 76 views
16

我們在SWIFT 2.2這樣的功能,打印日誌信息與當前正在運行的線程:如何獲得當前隊列名稱在迅速3

func MyLog(_ message: String) { 
    if Thread.isMainThread { 
     print("[MyLog]", message) 
    } else { 
     let queuename = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))! // Error: Cannot convert value of type '()' to expected argument type 'DispatchQueue?' 
     print("[MyLog] [\(queuename)]", message) 
    } 
} 

這些代碼不再SWIFT 3.0編譯。我們現在如何獲得隊列名稱?


這個問題關於如何確定兩個線程在同一個線程中的位置:Check if on correct dispatch queue in Swift 3。接受的答案建議使用setSpecific將「標籤」與創建的隊列關聯。但是,這並不能解決問題,因爲我們想知道隊列名稱。隊列可能不一定是由我們自己創建的。

+2

的可能的複製[檢查是否正確上調度隊列中的斯威夫特3](http://stackoverflow.com/questions/37952262/check-if-on-correct -dispatch-queue-in-swift-3) – ozgur

回答

22

由於布倫特皇家 - 戈登在他messagelists.swift.org提到它在當前設計一個洞,但你可以使用這個可怕的解決方法。

func currentQueueName() -> String? { 
     let name = __dispatch_queue_get_label(nil) 
     return String(cString: name, encoding: .utf8) 
    } 
+4

請編輯更多信息。僅限代碼和「嘗試這個」的答案是不鼓勵的,因爲它們不包含可搜索的內容,也不解釋爲什麼有人應該「嘗試這個」。我們在這裏努力成爲知識的資源。 –

+2

好的,我會那樣做的。 – Huralnyk

+0

不幸的是,這是唯一有效的答案。 –

4

如果你不喜歡不安全的指針和C字符串,還有另外一個,安全的解決方案:

if let currentQueueLabel = OperationQueue.current?.underlyingQueue?.label { 
    print(currentQueueLabel) 
    // Do something... 
} 

我不知道任何情況下,當currentQueueLabelnil

+0

如果隊列不是由我們自己創建的,標籤會是什麼?你見過這個問題嗎? https://stackoverflow.com/questions/37952262它有關係嗎? @kelin –

+0

1.標籤將類似「com.apple.main-thread」。 2.這是關於測試和它是相關的,但沒有你的問題的直接答案。 – kelin

+0

此解決方案似乎無法正常工作。對於同一個隊列,'OperationQueue.current?.underlyingQueue?.label'返回「com.apple.main-thread」,而'String(cString:__dispatch_queue_get_label(nil),encoding:.utf8)'返回「myDispatchQueueLabel」 – dodgio

0

這個最適合我:

/// The name/description of the current queue (Operation or Dispatch), if that can be found. Else, the name/description of the thread. 
public func queueName() -> String { 
    if let currentOperationQueue = OperationQueue.current { 
     if let currentDispatchQueue = currentOperationQueue.underlyingQueue { 
      return "dispatch queue: \(currentDispatchQueue.label.nonEmpty ?? currentDispatchQueue.description)" 
     } 
     else { 
      return "operation queue: \(currentOperationQueue.name?.nonEmpty ?? currentOperationQueue.description)" 
     } 
    } 
    else { 
     let currentThread = Thread.current 
     return "UNKNOWN QUEUE on thread: \(currentThread.name?.nonEmpty ?? currentThread.description)" 
    } 
} 



public extension String { 

    /// Returns this string if it is not empty, else `nil`. 
    public var nonEmpty: String? { 
     if self.isEmpty { 
      return nil 
     } 
     else { 
      return self 
     } 
    } 
}