Zakman411
Zakman411

Reputation: 1764

Opening 'New' Document?

I have some code implemented in my myDocument.m file that simply attempts to load the last used document upon launch. However, upon launching from a fresh install, (or running after deleting the last used file) a 'new' document window does not appear. Does anyone know what to add to my code to do this? Here it is:

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

Upvotes: 2

Views: 786

Answers (2)

Justin Meiners
Justin Meiners

Reputation: 11113

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

EDIT

I changed it and tried it out it should work now.

Upvotes: 1

user557219
user557219

Reputation:

What is docController, and why are you sending -openDocumentWithContentsOfURL:display:error: twice? Note that that method returns a document, not a URL, so using the return value as a URL wouldn’t work anyway.

The following is a cleaner, equivalent code:

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

However, it still doesn’t explain why you don’t get an untitled document. What happens if you comment out -applicationShouldOpenUntitledFile: so that the application follows standard Cocoa behaviour? It could be the case that the problem lies elsewhere.

Upvotes: 0

Related Questions