I try to understand a few things in Cocoa but I got stuck on one thing. I'm following Minimalistic Cocoa Programming, there it is a NSMenuItem
responsible for terminating the app. Now, I would like to create another NSMenuItem
, with a shortcut, that when pressed, it NSLog
-s something. But I don't know where should I put the implementation of said selector? Should I subclass the whole NSApplication
? Should I setDelegate
to some NSObject
instance, acting as a controller?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You need to create a class that can be used as the target of the menu item. Something like this:
@interface Tester : NSObject
@end
@implementation Tester
- (void)logTest:(id)sender
{
NSLog(@"Test");
}
@end
Then set it as the target:
id testMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Log Test" action:@selector(logTest:) keyEquivalent:@"l"] autorelease];
id tester = [[[Tester alloc] init] autorelease];
[testMenuItem setTarget:tester];