Untitled Document从模板打开

时间:2014-04-24 13:10:51

标签: macos cocoa nsdocument

在无标题文档的位置,我想在我的应用包中加载一个给定的文档,让它表现得像无标题

在NSDocumentController中覆盖此方法,但有一个问题,只要我关闭无标题文档,文件就会从包中删除...

- (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;
}

如何从保存在应用包中的“模板”文档中“加载”无标题文档?

1 个答案:

答案 0 :(得分:1)

当使用-initForURL:withContentsOfURL:ofType:error:作为初始网址调用nil时,这通常是sourceURL将成为未保存的自动保存文件的信号,如果您最终没有保存将被删除(如果你保存,它将被移动)。

我建议您初始化文档,然后使用文档的read方法之一来读取内容并覆盖空文档。如果您希望在执行此操作后轻松放弃这些内容(即,如果您不对模板文档进行更改,则不会保存提示),您可能需要使用NSChangeCleared设置updateChangeCount:

例如(插入代替当前的Document init行:

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;