NSDocument: The document could not be autosaved. The file has been changed by another application

1.6k views Asked by At

A search on the title of this post reveals that it's pretty common; indeed, I've gotten this error from Xcode. But I can't seem to find any fixes. I'm seeing it now when I run my program, and it appears to occur during or after changeCountTokenForSaveOperation is called. It seems related to the undo manager, rather than to the fact that i'm using core data, but I may be wrong.

Does anyone know what causes this or how to fix it?

3

There are 3 answers

7
93sauu On

The problem is saving manually the managedObjectContext. So the correct solution is avoid saving manually. If you cannot avoid it, you can override fileModificationDate method of NSDocument to return the current file modification date of the file. Of this way the document does not show the error message.

- (NSDate *)fileModificationDate {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *attrs = [fileManager attributesOfItemAtPath:self.fileURL.path error:NULL];
    return attrs[NSFileModificationDate];
}
0
Howard Cohen On

I think it has to do with the fact that you can navigate to other files by apple-clicking a method name. If you make changes in one file and then navigate to another it leaves the previous window behind. You can click the "back" triangle to reach it again (that is just above the upper left corner of the file window). But, if it had unsaved changes in that now-eclipsed window and you edit the same file again in a different tab or window XCode is going to ask you which one to keep with the above message.

When it happens, I copy the file on disk to a new name and then choose "Save Anyway" and compare the two files. Unfortunately, sometimes there are important changes in each file and I have to merge them by hand.

I'm so frustrated by this I could cry.

4
Ely On

This error can occur with NSPersistentDocument when you perform a manual save in code on the managedObjectContext of your NSPersistentDocument class. The problem here is you're modifying the document on disk behind NSPersistentDocument's back. Just leave the save actions to the NSPersistentDocument and the error will not occur.