Search code examples
cocoanskeyedarchivernsdocumentnscoding

NSCoding and NSKeyedArchiving - "The document could not be loaded"


I have implemented the NSCoding protocol for my classes, and I am using the following code in my NSDocument subclass to save and load:

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
[[record window] endEditingFor:nil];
return [NSKeyedArchiver archivedDataWithRootObject:self];

}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError{
@try {
    NSLog(@"Loading...");
    self = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
@catch (NSException *exception) {
    if (outError) {
        NSDictionary *d = [NSDictionary dictionaryWithObject:@"The data is corrupted" forKey:NSLocalizedFailureReasonErrorKey];
        *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:d];
    }
}
NSLog(@"whiteMoves count: %ld",[whiteMoves count]);

}

It all seems to be working fine. I can save a file and when I open it and step through the code it all seems to unarchive and decode fine. However, on completion of the 'load event' my application always pops up an error window that says "The document "xxx.xxx" could not be loaded." I cannot find where this error is being triggered from nor any documentation on it.

Does any one know where it comes from or know where it might be documented?

Thanks

Lee


Solution

  • You don't appear to be returning YES or NO from readFromData:

    - (BOOL)readFromData:(NSData *)data
                  ofType:(NSString *)typeName
                   error:(NSError **)outError
    {
        BOOL retval = YES;
        @try
        {
            NSLog(@"Loading...");
            self = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            NSLog(@"whiteMoves count: %ld",[whiteMoves count]);
        }
        @catch (NSException *exception)
        {
            if (outError != nil)
            {
                NSDictionary *d = [NSDictionary dictionaryWithObject:@"The data is corrupted" forKey:NSLocalizedFailureReasonErrorKey];
                *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:d];
            }
            retval = NO;
        }
    
        return retval;
    }
    

    This looks chess-related; can I ask what you are writing?