[英]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.