[英]Swift, NSOperationQueue.mainQueue(): update data in operation during operation is running?
我在IOS項目中使用后台文件下載,並且在開始文件下載時,通過方法中的塊NSOperationQueue.mainQueue().addOperationWithBlock()
啟動進度視圖的更新:
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown {
println("Unknown transfer size");
}
else{
let data = getDBInfoWithTaskIdentifier(downloadTask.taskIdentifier)
NSOperationQueue.mainQueue().addOperationWithBlock(){
data.db_info.downloadProgress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
let inf = data.db_info.indexPath
let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: data.index, inSection: 0)) as SettingsTableViewCell
cell.downloadProgress.hidden = false
cell.downloadProgress.setProgress(data.db_info.downloadProgress, animated: true)
}
}
}
當關閉帶有下載UI的視圖並再次顯示該視圖時, self.tableView
是新對象,但是更新進度視圖的NSOperationQueue.mainQueue()
操作中的self.tableView
是舊的,即關閉前的狀態。 Println()返回兩個不同的對象。 NSOperationQueue.mainQueue()
塊中是否有可能更新有關self.tableView
數據?
首先,您應該考慮切換到GCD(大中央調度)。
出現問題是因為在閉包中捕獲了對tableView
的引用。 您可以考慮將邏輯放在單獨的類函數中,這樣tableView
不會在您的閉包中公開。 它具有更簡潔,更有條理的代碼的另一個好處。
這是一個總體思路:
// new function
func setProgressInCell (data:?) { // '?' because i do not know the type
let inf = data.db_info.indexPath
let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: data.index, inSection: 0)) as SettingsTableViewCell
cell.downloadProgress.hidden = false
cell.downloadProgress.setProgress(data.db_info.downloadProgress, animated: true)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown {
println("Unknown transfer size");
}
else{
let data = getDBInfoWithTaskIdentifier(downloadTask.taskIdentifier)
dispatch_async(dispatch_get_main_queue()) {
[weak self] in
data.db_info.downloadProgress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
self.setProgressInCell(data)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.