Search code examples
objective-cswiftmacosnsdocumentnsmenu

Disable NSDocument's "Revert To" & "Duplicate" menu item


I am creating a Mac app to read a XML document and save it. Everything is working fine except "Revert To" & "Duplicate" menu items. Till i find a solution for that i want to disable both of them, but i didn't found any solution for it, Please let me know how can i disable both the options so that they end user cannot click on them.

I already looked into Menu's from .xib so that i can disable them but i don't see any options.

I tried to somehow manipulate below code, but i didn't found any answers.

override func duplicate() throws -> NSDocument { return self }


Solution

  • The general way to disable a menu item in Cocoa is returning false in validateMenuItem(_:) (or validateUserInterfaceItem(_:).)

    In this case, put the following code in your NSDocument subclass.

    override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
    
        guard let action = menuItem.action else { return false }
    
        switch action {
        case #selector(duplicate(_:)):
            return false
        case #selector(revertToSaved(_:)):
            return false
        default: break
        }
    
        return super.validateMenuItem(menuItem)
    }
    

    However, according to the Apple's Human Interface Guidelines, you should not leave menu items which are not used. So, if your app doesn't support duplication and revert features at all, I prefer to remove the items rather than to disable.