2016-04-21 142 views
0

我有一段代碼,其中可選項已初始化,然後在函數中爲其分配值,但在解包時爲nillSwift變量值和函數

var datastring: String? 
Alamofire.request(.POST, "https://example.url/request", parameters: parameters) .response { request, response, data, error in 
    datastring = NSString(data: data!, encoding:NSUTF8StringEncoding) as! String // there is data in here 
    // textView.text = datastring! datastring is not nill when here 
}  
textView.text = datastring! // datastring is nill when here 

這不是Alamofire特定的。在使用本地Swift方法時,我遇到了這個問題。我在做什麼錯,爲什麼Swift這樣工作?

PS。我還在學習:)

編輯:謝謝所有幫助我的人。爲了澄清問題,這是一個將變量的值從異步線程傳遞到主線程的問題。我只是不知道該怎麼說。

+3

datastring被設置在回調(異步)內部。同時,主線程繼續運行,因此當textView.text設置時,變量中沒有任何內容。您需要將您的值傳回給另一個回調中的主線程。 – ohiodoug

+0

[Alamofire request up up up nil]的可能重複(http://stackoverflow.com/questions/35372850/alamofire-request-coming-up-nil) – jtbandes

+0

@ohiodoug謝謝你解釋這一點。這是我不明白的。 –

回答

3

您正在更新閉包中的變量datastring。這是傳遞給Alamofire稍後執行的代碼(可能稍後幾微秒)。因此,在閉包執行之前,首先發生datastringtextView的行。

試試這個:

var datastring: String? 

Alamofire.request(.POST, "https://example.url/request", parameters: parameters).response { request, response, data, error in 
    datastring = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String 

    dispatch_async(dispatch_get_main_queue()) { 
     textView.text = datastring 
    } 
} 

使用dispatch_async調用確保用戶界面的更新發生在主線程。

網絡請求可能會在幾秒鐘(或更長時間)內不會發生,因此您可能需要使用臨時字符串更新UI,以便用戶在等待時看到某些內容。

+0

謝謝你解釋。你的和@ ohiodoug的解釋幫助了我很多。標記這個答案,因爲dispatch_async我需要回到主線程。 –

+0

真棒,很高興幫助。另外,由於你是Swift新手,儘量避免使用'!'。你應該考慮使用'!'作爲可能的崩潰點。我的團隊實際上稱他們爲「碰撞爆炸」。 –

+0

@DaveWood,'碰撞劉海' - 我喜歡那樣。 (哦,你好。) – NRitH

0

這兩條線

datastring = NSString(data: data!, encoding:NSUTF8StringEncoding) as! String // there is data in here 
textView.text = datastring! // datastring is not nill when here 

立即運行,因爲他們是一個封閉的內部。由Alamofire決定何時執行結案。