2016-03-07 119 views
2

如何在For/In循環中實現完成處理程序? 我有兩個CNLabeledContact的陣列稱爲phonesArrayFor/In循環中的完成處理程序 - swift

變種myPhoneNumberArray = CNLabeledValue

for item in phonesArray { 

    let phonesArrayValue = item.value as! CNPhoneNumber 
    let phonesArrayValueDigits = phonesArrayValue.valueForKey("digits")! 
    print("current value: \(phonesArrayValueDigits)") // 

    DataService.dataService.checkIfPhoneExistsInDatabase("\(phonesArrayValueDigits)") { (bool) in  
      if bool { 
       print("append this item") 
       self.myPhoneNumberArray.append(item) 
      } 
      else { 
      } 
    } 
} 
print("My phonenumbers array is:") 
print(myPhoneNumberArray) 

此,跑步,打印:

current value: 37439 
current value: 78735 
My phonenumbers array is: 
[] 
append this item //Only the second number matches the database and is appenned 

我想:

current value: 37439 
Current value: 78735 
append this item 
[<CNLabeledValue:....digits=78735>>] 
+1

我的猜測是'checkIfPhoneExistsInDatabase'是異步的,所以直到後來纔打印結果。如果你想正確打印,請將'print(「當前值:\(phonesArrayValueDigits)」)'移到'if bool {'上方。 – erdekhayser

+0

你是對的,但我簡化了我的問題太多。我將編輯我的問題。 – standousset

回答

1

看起來好像checkIfPhoneExistsInDatabase正在執行異步作業。因此,其餘的代碼可以在您的完成處理程序之前,之後或之間隨時運行。

因此,如果您的DataService實例不提供同步操作或某種同步,則必須在完成塊中手動執行該作業。您的主要興趣點是檢查是否所有項目都已處理。注意比賽條件。

另一個想法是序列化查詢,基本上將循環拖入完成處理程序中:只對第一個元素執行查詢,並在塊內查詢下一個元素的數據等等。