繁体   English   中英

swift中的完成关闭似乎没有被解雇

[英]Completion closure in swift doesn't appear to be firing

我正在关注O'reilly的“Learning Swift”一书,我有一些代码如下:

func deleteDocumentAtURL(url: NSURL) {
    NSLog("Got to top of deleteDocumentAtURL, url: \(url)")
    let fileCoordinator = NSFileCoordinator(filePresenter: nil)
    fileCoordinator.coordinateWritingItemAtURL(url, options: .ForDeleting, error: nil, byAccessor: { (urlForModifying) -> Void in
        NSLog("Here I am")
        do {
            NSLog("Got inside deleteDocumentBlock")
            try NSFileManager.defaultManager().removeItemAtURL(urlForModifying)

            // Remove the URL from the list
            self.availableFiles = self.availableFiles.filter {
                $0 != url
            }

            // Update the collection
            self.collectionView?.reloadData()

        } catch let error as NSError {
            let alert = UIAlertController(title: "Error deleting", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "Done", style: .Default, handler: nil))

            self.presentViewController(alert, animated: true, completion: nil)
        }
    })
}

当我运行此代码(通过单击界面中的按钮触发)时,应用程序将挂起。 另外,do {}内的日志没有触发,这让我觉得整个块都有问题? 帮助赞赏。

因为

let fileCoordinator = NSFileCoordinator(filePresenter: nil)

在函数中是本地的。 如果您完成了该功能,则该变量已被销毁。 因此,无法执行异步块。

fileCoordinator作为实例变量放到类中。

您没有处理错误,可能有错误

coordinateReadingItemAtURL的文档

outError:输入时,指向错误对象指针的指针。 如果文件演示者在准备此读取操作时遇到错误,

在此参数中返回该错误,并且不执行reader参数中的块。

如果在执行读取器块之前取消此操作,则此参数在输出时包含错误对象。

添加错误处理程序,看看是否收到错误

func deleteDocumentAtURL(url: NSURL) {
    NSLog("Got to top of deleteDocumentAtURL, url: \(url)")
    let fileCoordinator = NSFileCoordinator(filePresenter: nil)
    var error: NSError?
    fileCoordinator.coordinateWritingItemAtURL(url, options: .ForDeleting, error: &error, byAccessor: { (urlForModifying) -> Void in
        NSLog("Here I am")
        do {
            NSLog("Got inside deleteDocumentBlock")
            try NSFileManager.defaultManager().removeItemAtURL(urlForModifying)

            // Remove the URL from the list
            self.availableFiles = self.availableFiles.filter {
                $0 != url
            }

            // Update the collection
            self.collectionView?.reloadData()

        } catch let error as NSError {
            let alert = UIAlertController(title: "Error deleting", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "Done", style: .Default, handler: nil))

            self.presentViewController(alert, animated: true, completion: nil)
        }

    })
    //Error:
    if(error != nil){
        print(error)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM