Question

In the place of the untitled document, i want to load a given document in my app bundle and let it behave like untitled

Overriding this method in NSDocumentController, works, but with one problem, as soon as i close the untitled document, the file gets deleted from the bundle...

- (id)makeUntitledDocumentOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError {

    NSString * extension = @"aaa";
    NSString * untitledFilePath = [[NSBundle mainBundle] pathForResource:@"untitled" ofType:extension];
    NSURL * sourceUrl = [[NSURL alloc] initFileURLWithPath:untitledFilePath];

    Document * document = [[Document alloc] initForURL:nil withContentsOfURL:sourceUrl ofType:typeName error:outError];
    return document;
}

How to "load" the untitled document from a "template" document saved in app bundle?

Was it helpful?

Solution

When -initForURL:withContentsOfURL:ofType:error: is called with nil as the initial URL, that's usually a signal the the sourceURL is going to be an unsaved Autosave file, which if you don't eventually save will be deleted (and if you do save, it'll be moved).

I would suggest that you initialize the document and then use one of the read methods of document to read in the contents and override the empty document. If you want those to be easily abandoned after doing so (i.e. no save prompt if you don't make changes to the template document), you may need to set NSChangeCleared using updateChangeCount:.

For example (inserted in place of your current Document init lines:

NSError *error;
Document *document = [[Document alloc] initWithType: extension error: &error];
if (document) {
    // load template
    if (![document readFromURL: sourceURL ofType: extension error: &error]) {
         // do something appropriate to abort the load
    }
    [document updateChangeCount: NSChangeCleared]; // don't prompt for save w/o changes
}
return document;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top