Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Respond to Open Recent clicks in NSMenu

Tags:

cocoa

nsmenu

I am trying to respond to a user clicking an item in the Open Recent menu in my non-document based Cocoa app. I can handle File->Open by attaching it to an IBAction in IB. However, I cannot figure out how to handle when a user clicks something from the Recent list. Do I need a delegate of some sort?

like image 813
user1032657 Avatar asked Dec 26 '22 19:12

user1032657


1 Answers

'fraid this is a bit late, but on the off-chance you still need an answer:

I use the [NSDocumentController sharedDocumentController] to do all my lifting. The documentation's here. Your project doesn't have to be document-based.

Set up an NSDocumentController variable in your header:

NSDocumentController *theDocCont;

Then implement something like the following in your main AppDelegate file:

-(void)addToRecent:(NSArray*)URLs
{
    if (!theDocCont) {
        theDocCont = [NSDocumentController sharedDocumentController];
    }
    [URLs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [theDocCont noteNewRecentDocumentURL:obj];
    }];
}

-(void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
{
    [self openItems:filenames addToRecents:NO]; //see later
}

You can now add to the Recents menu by calling [self addItems:[myNSOpenPanel URLs] addToRecents:YES]; from the completion block of an NSOpenPanel.

Basically, the -addToRecent: method should be given an NSArray of NSURLs. Then they're added to the standard 'Open Recents' menu item (that comes gift-wrapped in the main.xib file when you first set up your project) by the -noteNewRecentDocumentURL:.

When the app's running and you click on an item in that menu the OS will look for the implementation of -application:openFiles: (if it doesn't find it there'll be an NSAlert along the lines of "yourApp can't open files of this type"). fileNames will be an NSArray of NSURLs.

You'll probably want to handle the opening of URLs differently but I've shown mine as it highlights a small issue where (like I initially did) you try to add a Recent item during the call to -application:openFiles:. In my project, I have a communal method to handle the opening of URLs which is called from various parts of the app and also by default adds the URL(s) being opened to the Recents list; but I don't want to re-add an item that's already coming from the 'Open Recents' menu, hence the reason for the addToRecents: part of the signature. If you try to do that there'll be a crash - I suppose it's like an infinite feedback loop!

like image 118
Todd Avatar answered Feb 19 '23 05:02

Todd