Search code examples
cocoasavensdocumentversionsrevert

NSDocument Versions has weird behavior


Saving and Opening of file works perfect, but when selecting 'Revert To Save', on the right side of windows (previous documents) for a blink of second my document versions are seen then just blank copies. And if I restore from this blah copy noting is changed but if I save and reopen the document it is restored to the previous version. I am not sure how it is happening. I have checked the official Apple document and WWDC videos but I am not near to solving this. Please help?

In my NSDocument subclass, I have implemented this methods:

+ (BOOL)autosavesInPlace { return YES; }
+ (BOOL)preservesVersions { return YES; }

and reading from file is done:

- (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError {

if ([typeName compare:@"public.plain-text"] == NSOrderedSame) {
    doucmentString = [[NSString alloc] initWithContentsOfURL:absoluteURL encoding:NSUTF8StringEncoding error:outError];
return YES;
}
if ( outError != NULL ) {
    *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return NO;
}

And in Windows Controller did load I am setting the string to MyDocument which is IBOutlet to NSTextview:

- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
[super windowControllerDidLoadNib:aController];
[myDocument insertText:doucmentString];
[self updateChangeCount:NSChangeAutosaved];
}

UPDATE:

I have solved the version browser behavior by moving the windowsControllerDidLoadNib code to the awakeFromNib. So now I can see the document versions. Phew!

Still when hitting restore, my document doesn't get updated, only when closing and reopening they are show. There must be some updating code that i don't know about. So still looking!


Solution

  • Finally everything is working in versions: I am using this method:

    - (BOOL)revertToContentsOfURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError {
        if(absoluteURL != NULL) {
        doucmentString = [[NSString alloc] initWithContentsOfURL:absoluteURL encoding:NSUTF8StringEncoding error:outError];
        return YES;
        } else if (outError) {
          //do nothing
        }
        return NO;
      }
    

    and also changed my awakeFromNib method, instead of insertText I now use insertTextreplacementRange

    -(void) awakeFromNib
    {
      if (documentString != NULL) {
      [myDocument insertText:doucmentString replacementRange:NSMakeRange(0, [[myDocument textStorage]length])];
      [self updateChangeCount:NSChangeAutosaved];
      }
    }