2016-04-22 13 views
0

MLPAutoCompleteTextFieldデリゲートメソッドでネットワーク操作後に配列を返す必要があります。これに関する提案は非常に役に立ちます。代わりにコールバッククロージャの成功と失敗のデリゲートメソッドを持つiOS:ネットワーク操作後に関数から値を返します。

func autoCompleteTextField(textField: MLPAutoCompleteTextField!, possibleCompletionsForString string: String!, completionHandler handler: (([AnyObject]!) -> Void)!) { 
    //Perform network operation. Success and Failure conditions are handled below by implementing the protocol 
    service.getData(string) 

    //Have to return this only after network operation is completed either success or failure 
    handler(autoCompleteSuggestionsArray) 
} 

//Handle successful network call 
func handleSuccess(model: Model) { 
    autoCompleteSuggestionsArray.removeAll() 
    for item in model.items { 
     if let itemName = item.name { 
      autoCompleteSuggestionsArray.append(itemName) 
     } 
    } 
} 

//Handle failed network call 
// 
func handleErrorWithMessage(message: String) { 
    autoCompleteSuggestionsArray.removeAll() 
} 

答えて

0

はあなたの例に示されている理由のための素晴らしい方法ではありません:あなたは、デリゲートメソッドであなたのautoCompleteTextField法の適用範囲から引数を含めることはできません。デリゲートを使用する代わりに、サービスの実装を変更してクロージャを使用できる場合。 service.getData(string:String, success:SuccessClosure, failure:FailureClosure)、これは全体的により良い状況になります。

あなたがその変更を行うことができない場合は、あなたが不幸な何かをする必要があり、このように:

var autocompleteHandler:([AnyObject]->())? //Create a new property on your class to hold an optional reference to the handler that is visible to multiple methods 

func autoCompleteTextField(textField: MLPAutoCompleteTextField!, possibleCompletionsForString string: String!, completionHandler handler: (([AnyObject]!) -> Void)!) { 
    //Save reference to handler in scope that is also visible to delegate methods 
    autocompleteHandler = handler 

    //Perform network operation. Success and Failure conditions are handled below by implementing the protocol 
    service.getData(string) 
} 

//Handle successful network call 
func handleSuccess(model: Model) { 
    autoCompleteSuggestionsArray.removeAll() 
    for item in model.items { 
     if let itemName = item.name { 
     autoCompleteSuggestionsArray.append(itemName) 
     } 
    } 
    // Now that we have a result from the service, pass it to the saved handler if it is not nil 
    autocompleteHandler?(autocompleteSuggestionsArray) 
} 

//Handle failed network call 
func handleErrorWithMessage(message: String) { 
    autoCompleteSuggestionsArray.removeAll() 
    // Now that we have a result from the service, pass it to the saved handler if it not nil 
    autocompleteHandler?(autocompleteSuggestionsArray) 
} 
+0

あなたは私の一日行われ...ありがとう!私はservice.getData(string:String、success:SuccessClosure、failure:FailureClosure)を使用できません。これは、多くのコントローラで使用されているグローバルサービスであり、同じことを続ける必要があるためです。ハンドラを変数に保存し、それを渡す際のあなたの提案。 –

関連する問題