Hi everyone
I am trying to implement a template / stationary system via a subclass of NSDocumentController. Not much can be found about this topic via google, unfortunately. I tried the following, but each approach brings its own problem. Maybe you have a solution?
I am trying to implement a template / stationary system via a subclass of NSDocumentController. Not much can be found about this topic via google, unfortunately. I tried the following, but each approach brings its own problem. Maybe you have a solution?
Code:
#pragma mark -
#pragma mark templates
-(id) openUntitledDocumentFromTemplate:(NSURL *) url
error:(NSError **) outError
{
/**
Create a new document from a template.
Calls makeUntitledDocumentOfType and revert to previous saved document a.k.a. template
Calls defaultTemplate when template is nil.
*/
id newDoc = nil;
if (!url)
url = [self defaultTemplate];
NSString *templateDocumentType = [self typeForContentsOfURL:url
error:outError];
if (*outError != NULL)
return nil;
@try {
#if 0
newDoc = [[NSDocumentController sharedDocumentController] reopenDocumentForURL:nil
withContentsOfURL:url
error:outError]; //deletes original
if (*outError != NULL) @throw [NSException exceptionWithName:@"MyDocumentController"
reason:@"Can not load data from template"
userInfo:nil];
#endif
#if 0
newDoc = [[NSDocumentController sharedDocumentController] makeDocumentForURL:nil
withContentsOfURL:url
ofType:templateDocumentType
error:outError];
[newDoc makeWindowControllers];
[newDoc showWindows]; //window disappears immediately
if (*outError != NULL) @throw [NSException exceptionWithName:@"MyDocumentController"
reason:@"Untitled document can not be created."
userInfo:nil];
#endif
#if 1
newDoc = [[NSDocumentController sharedDocumentController] makeUntitledDocumentOfType:templateDocumentType
error:outError];
if (*outError != NULL) @throw [NSException exceptionWithName:@"MyDocumentController"
reason:@"Untitled document can not be created."
userInfo:nil];
[newDoc revertToContentsOfURL:url
ofType:templateDocumentType
error:outError]; //this automatically displays the window
if (*outError != NULL) @throw [NSException exceptionWithName:@"MyDocumentController"
reason:@"Can not load data from template"
userInfo:nil];
[[newDoc undoManager] disableUndoRegistration];
[newDoc setFileURL:nil];
[[newDoc undoManager] removeAllActions]; //still possible to do undo/ctrl-z one more time. Should be zero in the ideal solution
// [[newDoc undoManager] enableUndoRegistration]; //removeAllActions reenables undomanager, so this line is unnecessary. If uncommented, the document will appear only briefly
#endif
}
@catch (NSException * exception)
{
[self removeDocument:newDoc];
newDoc = nil;
}
return newDoc;
}