2011-02-09 134 views
2

我在我的myDocument.m文件中实现了一些代码,它只是在启动时尝试加载上次使用的文档。但是,从全新安装启动后(或在删除之后运行上次使用的文件),不会显示“新”文档窗口。有谁知道要添加到我的代码来做到这一点?那就是:打开'新'文档?

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender 
{ 
    NSURL *lastURL=[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:lastURL display:YES error:nil]; 
    if (lastURL!=nil) 
    { 
    [docController openDocumentWithContentsOfURL:lastURL display:YES error:nil];  
     return NO; 
    } 

    return YES; 
} 

回答

1
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender 
{ 
    NSArray* urls = [[NSDocumentController sharedDocumentController] recentDocumentURLs]; 
    if ([urls count] > 0){ 
     NSURL *lastURL= [urls objectAtIndex: 0]; 

     if ([[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:lastURL display:YES error:nil]){ 
        return NO; 
      }  

    } 

    return YES; 
} 

编辑

我改变了它,并尝试过了,现在应该工作。

+0

@Justin - 它的工作原理是打开最后使用的文档,但是当我清除列表并打开应用程序时,我想要一个新的文档出现 – Zakman411 2011-02-09 02:34:30

+0

我明白了,只是试了一下。之前引发了一个例外,但我修复了它。 – 2011-02-09 02:38:43

0

docController什么是,你为什么发送-openDocumentWithContentsOfURL:display:error:两次?请注意,该方法返回一个文档,而不是一个URL,所以使用返回值作为URL将无法正常工作。

下面是一个更清洁,等效代码:

- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender 
{ 
    id lastDoc = [[NSDocumentController sharedDocumentController] 
     openDocumentWithContentsOfURL:lastURL 
     display:YES error:NULL]; 
    return (lastDoc == nil); 
} 

但是,它仍然不能解释为什么你没有得到一个未命名的文档。如果您注释掉-applicationShouldOpenUntitledFile:以便应用遵循标准Cocoa行为,会发生什么情况?问题可能出在其他地方。