我有一个待办事项列表应用程序,将文档存储在 iCloud 中UIDocument
目的。表视图控制器中创建以下函数,用于在 iCloud 中本地和远程删除待办事项列表项but通过在表格视图单元格上滑动删除手势来执行应用程序时挂起应用程序:
fileprivate func deleteNote(at indexPath: IndexPath) {
let noteDocument = self.noteDocuments[indexPath.row]
let fileCoordinator = NSFileCoordinator(filePresenter: nil)
fileCoordinator.coordinate(writingItemAt: noteDocument.fileURL,
options: NSFileCoordinator.WritingOptions.forDeleting,
error: nil) { [weak self] (passedURL: URL) in
guard let weakSelf = self else { return }
do {
try FileManager.default.removeItem(at: passedURL)
weakSelf.noteDocuments.remove(at: indexPath.row)
weakSelf.tableView.deleteRows(at: [indexPath], with: .bottom)
weakSelf.tableView.reloadData()
}
catch let error as NSError {
print("Error occured deleting a document. Reason: \(error.localizedDescription)")
}
}
}
The iOS 基于文档的编程指南 http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/DocumentBasedAppPGiOS/ManageDocumentLifeCycle/ManageDocumentLifeCycle.html文件中所述删除文档 http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/DocumentBasedAppPGiOS/ManageDocumentLifeCycle/ManageDocumentLifeCycle.html#//apple_ref/doc/uid/TP40011149-CH4-SW4删除 iCloud 中的项目应在后台线程中异步执行的部分。所以我封装了NSFileCoordinator
使用 GCD 实例化如下,但每次执行删除操作后,它都会短暂消失然后重新出现(我可以在 iCloud Drive 中看到这种情况发生)。所以,本质上,它不会被删除。
fileprivate func deleteNote(at indexPath: IndexPath) {
let noteDocument = self.noteDocuments[indexPath.row]
DispatchQueue.global(qos: .default).async {
let fileCoordinator = NSFileCoordinator(filePresenter: nil)
fileCoordinator.coordinate(writingItemAt: noteDocument.fileURL,
options: NSFileCoordinator.WritingOptions.forDeleting,
error: nil) { (passedURL: URL) in
do {
try FileManager.default.removeItem(at: passedURL)
}
catch let error as NSError {
print("Error occured deleting a document. Reason: \(error.localizedDescription)")
}
}
}
self.noteDocuments.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
self.tableView.reloadData()
}
我能成功删除它的唯一方法实际上是not遵循 指南。我不使用NSFileCoordinator
coordinate(writingItemAt:options:error:byAccessor:)
我不会在后台线程中异步设置删除操作DispatchQueue
global(qos:)
像这样
fileprivate func deleteNote(at indexPath: IndexPath) {
let noteDocument = self.noteDocuments[indexPath.row]
do {
try FileManager.default.removeItem(at: noteDocument.fileURL)
}
catch let error as NSError {
print("Error occurred deleting a document. Reason: \(error.localizedDescription)")
}
self.noteDocuments.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
self.tableView.reloadData()
}
有什么指示可以说明我可以采取哪些措施来实现符合 指南,同时仍然能够成功执行删除操作?谢谢。