gpt4 book ai didi

ios - swift ,NSOperationQueue.mainQueue() : update data in operation during operation is running?

转载 作者:行者123 更新时间:2023-11-28 09:18:24 27 4
gpt4 key购买 nike

我在IOS项目中使用后台文件下载,当文件下载开始时,进度 View 的更新由 block 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 的 View 被关闭并再次出现时,self.tableView是新对象,但是 self.tableViewNSOperationQueue.mainQueue()更新进度 View 的操作是旧操作,即解雇之前的操作。 Println() 返回两个不同的对象。关于self.tableView是否有可能更新数据在那NSOperationQueue.mainQueue()阻止?

最佳答案

首先,您应该考虑切换到 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)

}
}
}

关于ios - swift ,NSOperationQueue.mainQueue() : update data in operation during operation is running?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26431108/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com