2014-10-17 110 views
1

我使用的背景文件下載在IOS項目,並在文件下載開始,發展觀的更新塊NSOperationQueue.mainQueue().addOperationWithBlock()的方法啓動:Swift,NSOperationQueue.mainQueue():在操作過程中更新數據在運行嗎?

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是新的對象,但self.tableViewNSOperationQueue.mainQueue()操作,更新進度視圖,是舊的,那是什麼之前解僱。 Println()返回兩個不同的對象。是否有可能更新NSOperationQueue.mainQueue()區塊中有關self.tableView的數據?

回答

0

首先您應該考慮切換到GCD(Grand Central Dispatch)。

您的問題出現了,因爲在閉包中捕獲了對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) 

     } 
    } 
} 
+0

我發現爲什麼它老'self.tableView',這是因爲後臺會話仍然駁回觀爲代表,而不是新的,我沒有想法,是否有可能更新NSURLSession委託或不。即使使用你的代碼,URLSession處理被駁回的視圖,並且沒有與新呈現的連接。 – voluntas88 2014-10-18 10:12:40

相關問題