2016-03-14 21 views
-1

需要添加一個(相同)函數中兩行的執行之間完成。是否有任何有利的選擇來做到這一點?添加完成之間執行兩個以下行swift

如:

line 1: [executing first operation]; 

line 2: Complete first operation 

line 3: when first operation is compeleted -> [executing second operation]; 

任何幫助是明顯的。在此先感謝...

+0

對此類執行使用Closure。參考鏈接:http://www.learnswift.io/blog/2014/6/9/writing-completion-blocks-with-closures-in-swift – Pushpa

回答

1

解決方案

您可以使用封閉了點。結帳here

實施

在這裏,你有你的聲明函數的代碼。

讓我們說,第一操作是執行在後臺線程指令的功能(即我們做一個網絡請求,我們等待迴應。我們等待它讓我們的數據,所以我們使用completionHandler,這是一個封閉,這將被調用時,我們對第一操作完成。

籲請第一操作指示,我們會​​得到將要執行的回調時爲的說明第一次操作完成。當它返回時finished是真的,那麼我們很樂意去打電話給第二次手術。

宣言

// First operation 
func foo1(completionHandler: (finished: Bool) -> Void) { 
    // Considering that you are doing background stuff inside a block 
    let foo1Block = { 
     // Your instructions 
     //.... 

     // When finished 
     completionHandler(finished: true) 
    } 

    // Execute block 
    foo1Block() 
} 

// Second operation 
func foo2() { 
    // Your instructions 
} 

這裏是你怎麼稱呼它:

執行

foo1 { (finished) -> Void in 
    if (finished) { 
     // If the first operation is finished let's execute the next one 
     self.foo2() 
    } 
} 
0

您可以使用dispatch_group這一點。你不必等待,它更簡單。假設你有一個函數startFunction()和endFunction(),它代表你的行和行3,你可以這樣做。這是你可以做的一個樣本。

在本例中,startFunction()被調用,然後當您按下按鈕時,會自動調用endFunction。startFunction進入dispatch_group,但只有在按下按鈕時退出組。我這樣做是爲了模擬解決方案的異步性質。你可以根據你的需要調整它。

class ViewController: UIViewController { 

let dg = dispatch_group_create() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    startFunction() 
    dispatch_group_notify(dg, dispatch_get_main_queue()) { 
     self.endFunction() 
    } 
} 

func endFunction() { 
    print("endFunction") 
} 
func startFunction() { 
    dispatch_group_enter(dg) 
    print("startFunction") 
} 

@IBAction func buttonAction(sender:UIButton) { 
    dispatch_group_leave(dg) 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

}

基本上你使用一個調度組,並進入該組,做你的功能。之後,你離開小組。當所有調用dispatch_group_enter的代碼調用離開調度組時,還可以使用dispatch_notify執行塊。

相關問題