2016-03-08 56 views
-1

我有一個巨大而耗時的例程(calculatePower)需要一個完成處理程序,以便它同步運行。該請求的觸發器是一個UIButton。這就是所謂的:Swift完成處理程序調用語法

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) { 
    calculatePower() { 
     completionHandler(UIBackgroundFetchResult.NewData) 
     } 
} 

在calcualtePower完成處理的重要位讀作:

func calculatePower(completionHandler: (() -> Void)!) { 
    completionHandler() 
} 

有我得到這個權利,如果是的話,我稱應用程序()?

application() 

是不是。

回答

1

performFetchWithCompletionHandler不是你所說的。如果您已配置後臺下載,則運行時會調用它。你的情況似乎與後臺下載沒有任何關係(是嗎?),所以我會說你完全錯誤地吠叫了錯誤的樹。如果您想要將耗時的計算轉移到後臺,您需要了解GCD和後臺隊列(即dispatch_async)。之後您將很容易回到主線程(另一個dispatch_async)。

+0

,看到我的在線圖書:http://www.apeth.com/iOSBook/ch38.html#_grand_central_dispatch – matt

+0

我的工作我的方式通過 - 許多感謝。 –

0

解讀爲,非常感謝馬特。

@IBAction func buttonCalculatePower(sender: AnyObject) { 
    self.calculateButton.setTitle("Calculating", forState: .Normal) 
    self.calculateButton.backgroundColor = UIColor.lightGrayColor() 
    self.calculateButton.enabled = false 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
      self.calculatePower() 
      dispatch_async(dispatch_get_main_queue()) { 
       self.calculateButton.backgroundColor = UIColor.orangeColor() 
       self.calculateButton.setTitle("Start", forState: .Normal) 
       self.calculateButton.enabled = true 
     } 
    } 
}