Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validateMenuItem: not called

I'm facing a weird situation. I've got an NSMenu with a submenu in it. The submenu's contents are populated programmatically. In my validateMenuItem: method, I can see all items being checked (the parent's items) as well as the subitems (once I click on a submenu), except for those in my auto-populated submenu.

Why is that? Am I doing something wrong? Any ideas on how to fix that?

like image 890
Dr.Kameleon Avatar asked Mar 03 '13 10:03

Dr.Kameleon


2 Answers

Here is the solution :

Cocoa looks for the validateMenuItem: method in the Class where the NSMenuItem's action selector is.

So, if your NSMenuItem's action selector (e.g. @selector(someSelector:)) is implemented in SomeClass, then make sure you have a validateMenuItem: method in SomeClass too, if you want to validate the corresponding menu items.

like image 74
Dr.Kameleon Avatar answered Nov 20 '22 22:11

Dr.Kameleon


@Dr.Kameleon has the right answer.

I'll add one small point to update it if that's OK? My code broke recently in this area and stopped calling validateMenuItem: when it was working before. I didn't notice because the only symptom was a menu item no longer disabled when it should.

The issue was Swift 4. The method must be attributed with @objc. In earlier versions of Swift, inheriting from NSObject, NSViewController, etc. was enough but that changed with the newer versions of Swift, 4 and 5.

p.s. It seems it is fine to put the method in an extension.

like image 5
Carl Avatar answered Nov 20 '22 21:11

Carl