ios - 文档关闭后调用 Swift UIDocument 自动保存且类未取消初始化

标签 ios swift uidocument

App 具有从 CollectionViewController 创建的 UIDocument。 UIDocument 使用包装器和 autosaveWithCompletionHandler。

class myDocument: UIDocument {
    var wrapper: NSFileWrapper?
    var data: [Int] = []

    override internal func contentsForType(typeName: String) throws -> AnyObject {
        // called by doc.saveToURL
        return wrapper!
    }

func SaveMyData() {
    wrapper!.addRegularFileWithContents(.......)
    self.updateChangeCount(.Done) // which eventually calls 
    // autosaveWithCompletionHandler which calls saveToURL 
    // which calls contentsForType
}
}

创建 UIDocument 实例(和 viewController)的 UICollectionViewController 只保留来自应用程序目录和常用方法的 url 列表。

class DocChooserCollectionViewController: UICollectionViewController, UIGestureRecognizerDelegate {
    let myExtension = "whatever"
    var documents: [NSURL] = []
}

问题是:通过 UIDocument 方法保存的异步文件可以在 View Controller 关闭(几秒后)并解除分配并且用户再次看到 UICollectionViewController 之后很好地发生。捕获它并知道最终保存已经发生的正确方法是什么,从而将 wrapper 属性设置为 nil 并允许释放 UIDocument ?我猜想 viewController 的 deinit() 可以在 UIDocument 的实例中设置一个“完成”属性,但这听起来并不干净,而且仍然不知道何时将 wrapper 属性设置为 nil。

谢谢!

最佳答案

解决了文档保存异步和 UIDocument 内存释放问题。在 View Controller 中:

deinit {
    print("myViewController is being deinitialized")
    doc.CloseNow()
}

在我的 UIDocument 子类中:

func CloseNow() {
    self.closeWithCompletionHandler({(success) in
        if (success) {
            print("close succeeded")
        } else {
            print("close failed")
        }
    })
}

Instruments 显示正在释放内存,trace 显示正在保存 doc 并且 UIDocument 已取消初始化。

关于ios - 文档关闭后调用 Swift UIDocument 自动保存且类未取消初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35546214/

相关文章:

objective-c - UIDocument 无法再次关闭?

iphone - 如何设置iPhone视频输出图像大小

ios - 找不到字体(Swift)

ios - ARKit - 如何获取场景 View 中的特定节点?

ios - SKTileMapNode:检测触摸的 Tile?

ios - 无法使用 Xcode 8 和 Swift 3 以编程方式在 SpriteKit 中触发 segue

ios - 适用于 iCloud 的大量 UIDocuments

ios - 如何按修改日期对 UIDocument 的 icloud NSMetadataQuery 结果进行排序?

swift - 我需要帮助快速使用陀螺仪

swift - CloudKit - CKRecord.ID 可接受的记录名称?