简体   繁体   中英

Swift UIDocument autosave called after document closes and class doesn't deinit

App has UIDocument created from CollectionViewController. The UIDocument uses wrappers and 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
}
}

The UICollectionViewController that creates the UIDocument instance (and viewController) just keeps a list of urls from app's directory and the usual methods.

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

The question(s) are: the async file save through the UIDocument methods can happen well after the view controller is closed (seconds later) and deallocated and the user sees the UICollectionViewController again. What's the proper way to catch this and know the final save has happened, to thus set the wrapper property to nil and allow the UIDocument to be released? I guess the viewController's deinit() could set a 'done' property in the instance of the UIDocument, but that doesn't sound clean and still don't know when to set the wrapper property to nil.

Thank you!

Solved both the document saving async and UIDocument memory release issues. In the view controller:

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

And in my UIDocument subclass:

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

Instruments shows memory is being released, and trace shows doc is being saved and UIDocument is deinit-ed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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