UIDocument Recovers Unsaved Changes on Application Failure / Forced Termination

From what I understand, the UIDocument class can track unsaved changes in a file and even locks the file, so it cannot be checked by more than one person. But what happens if a user leaves the application without saving or the application crashes? How can I restore unsaved changes to a UIDocument so that when I re-launch the application, it opens the UIDocument again with the latest unsaved changes? Do I need to make duplicate copies of each file before changing it and change the temporary copy until the user saves the changes? Or does Apple offer a simpler implementation? I also considered encoding and storing the contents of the Data and undoManager each instance of UIDocument periodically as a cache. Will this work?

+5
source share
1 answer

UIDocument and UIManagedDocument automatically track changes (calling a function in which you can return true if the document was changed) and save the changes to disk, taking into account other system restrictions (for example: if another process tries to read the file). How Apple makes savings is very safe unless you override the base class methods. When the save operation is started, Apple saves the temporary file and, if the save is successful, it quickly renames and deletes the source file (IIRC rename / delete is atomic or almost atomic). You can assume that the save operation does not leave a damaged file in the file system for 99.99% of all cases.

Apple starts saving operations in the background at certain points (for example, time, the application switches to the background, before another process tries to access the file, ...), but I could not find a clear statement about what was happening when the application forcibly shuts down.

However, logic and common sense tell me that if you forcefully terminate the application, the current state of the document cannot be saved. Even manually implementing a โ€œquick saveโ€ for forced exit may be technically impossible. A better strategy would be to periodically save the background (for example, UIDocument).

About saving the state of the undo manager: This will be the same technical problem as when saving the UIDocument. There is no event or anything else that tells the application that it must be forced.

You should read the Apple Documentation . It takes a very long time, but it explains the process in more detail. My advice for you would be to implement the strategy that Apple offers. These strategies sound and work for many, many applications in the Apple ecosystem and for their users. In addition, you have a reduced implementation cost and automatic improvements (when Apple updates their implementation).

+1
source

All Articles