Using the "Open Recent" Menu in Cocoa Without NSDocument

This post was updated to include Swift syntax on February 27, 2018.

Many people probably already know this, but if you’re not using NSDocument in your Cocoa application, the “Open Recent” menu will not get populated automatically when you open files. There are two steps to getting the “Open Recent” menu to work correctly, which are documented in the NSDocumentController documentation, but if you’re searching for a way to do this on Google, the NSDocumentController documentation will not come up, and it’s not inherently obvious that you should look in the NSDocumentController documentation, and searching the XCode documentation for “Open Recent” returns no results.

First, you need to tell NSDocumentController to add the file to the menu. In Swift, you need to call NSDocumentController.shared.noteNewRecentDocumentURL(URL(fileURLWithPath: filePath)). In Objective-C, call [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:filename]];. You can call this at any time after you have the filename, but it might be best to make sure that you can open the file and read it before adding it to the menu.

Next, in Swift, you need to implement func application(_ sender: NSApplication, openFile filename: String) -> Bool in your NSApplication delegate. In Objective-C, the method signature is - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename. This method gets called when the user selects an item from the “Open Recent” menu, so its implementation should open the file or call another method which opens the file. If this method returns NO, the file will be removed from the “Open Recent” menu. If it returns YES then the file will be kept in the menu.