搜尋

首頁  >  問答  >  主體

objective-c - 閉包導致的時間問題怎麼解決?

例如

func hello() -> Bool {
    var result = false
    httpRequestWithCompletionHandler({ is404 in
        result = is404
    })
    return result
}

這個函數的回傳值永遠是 false,因為 closure 是異步執行的
怎麼在呼叫這個函數的時候,得到真正的回傳值呢?
註: result 必須定義在函數體內,不能定義在函數體外

伊谢尔伦伊谢尔伦2879 天前741

全部回覆(2)我來回復

  • 大家讲道理

    大家讲道理2017-04-24 09:12:38

    var result_cb = function (result) { alert(result) };
    
    function hello(cb) {
        httpRequestWithCompletionHandler(is404) {
            cb(is404);
        }
    }
    
    hello(result_cb);
    

    這樣?

    回覆
    0
  • 迷茫

    迷茫2017-04-24 09:12:38

    GO lang ? 非同步執行的函數只能透過回呼來獲得值,因此不能直接透過hello傳回bool的方式來獲得結果。

    回覆
    0
  • 取消回覆