簡體   English   中英

在主線程上調用方法?

[英]Calling a method on the main thread?

首先,我正在為 iphone 編寫代碼。 我需要能夠在不使用performSelectorOnMainThread的情況下調用主線程上的方法。 我不想使用performSelectorOnMainThread的原因是當我嘗試為單元測試創​​建模擬時它會導致問題。

[self performSelectorOnMainThread:@Selector(doSomething) withObject:nil];

問題是我的模擬知道如何調用doSomething但它不知道如何調用performSelectorOnMainThread

那么有什么解決方案嗎?

Objective-C

dispatch_async(dispatch_get_main_queue(), ^{
    [self doSomething];
});

迅速

DispatchQueue.main.async {
    self.doSomething()
}

舊版斯威夫特

dispatch_async(dispatch_get_main_queue()) {
    self.doSomething()
}

軟件中有一種說法,即添加一層間接層幾乎可以解決任何問題。

讓 doSomething 方法成為一個間接 shell,它只執行 performSelectorOnMainThread 來調用 real_doSomething 方法來執行實際的 Something 工作。 或者,如果您不想更改 doSomething 方法,請讓模擬測試單元調用 doSomething_redirect_shell 方法來執行類似操作。

這是在 Swift 中執行此操作的更好方法:

runThisInMainThread { () -> Void in
    // Run your code
    self.doSomething()
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

它作為標准功能包含在我的倉庫中,請查看: https ://github.com/goktugyil/EZSwiftExtensions

現在在 Swift 3 中:

DispatchQueue.main.async{
   self.doSomething()
}

現代 Swift 解決方案是使用 Actor 進行安全的多線程,即MainActor

@MainActor func setImage(thumbnailName: String) {
    myImageView.image = UIImage(image: thumbnailName)
}

我在這里概述了更多基於actor的主線程解決方案。

// Draw Line
    func drawPath(from polyStr: String){
        DispatchQueue.main.async {
            let path = GMSPath(fromEncodedPath: polyStr)
            let polyline = GMSPolyline(path: path)
            polyline.strokeWidth = 3.0
            polyline.strokeColor = #colorLiteral(red: 0.05098039216, green: 0.5764705882, blue: 0.2784313725, alpha: 1)
            polyline.map = self.mapVu // Google MapView
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM