janeh
janeh

Reputation: 3814

@selector - How to call a method from another class?

I had created an NSMenu via Interface Builder. One of the menu items called showPreferencesPanel method, which is defined in KBAppController.m:

-(void)showPreferencesPanel {
    //something
}

Now, I have to re-build the menu without IB...all programmatically. StatusMenu.m is the class that deals with all that, and I can't figure out the target that I should set so that a method is called from another class.

Creating an instance of that class didn't work! The menu item is grayed out.

StatusMenu.m

KBAppController *kbAppController = [[KBAppController alloc]init];
NSMenuItem* preferencesItem;
[preferencesItem setTarget:kbAppController];
preferencesItem = [[NSMenuItem alloc] initWithTitle:@"Preferences…" action:@selector(showPreferencesPanel) keyEquivalent:@""];

Edited:-------------------------------------------

Here is the updated code that uses an object of class KBAppController. The good news is that the prefs menu item is enabled, but it still doesn't call the method in KBAppController.m :(

KBStatusMenu.m

@synthesize kbAppController = _kbAppController;

someMethod {   
NSMenuItem* preferencesItem;
preferencesItem = [[NSMenuItem alloc] initWithTitle:@"Preferences…" action:@selector(showPreferencesPanel) keyEquivalent:@""];
[preferencesItem setTarget:self];
}

- (void)showPreferencesPanel {
NSLog(@"in 1");
[_kbAppController showPreferencesPanel];
}

KBAppController.m

-(void)showPreferencesPanel {
    NSLog(@"in 2");
    //something
}

Upvotes: 2

Views: 910

Answers (2)

James Paolantonio
James Paolantonio

Reputation: 2194

NSMenuItem has a - (void)setTarget:(id)anObject and - (void)setAction:(SEL)aSelector that should do that trick.

Just make sure you set up and init the NSMenuItem first. Right now you are calling -setAction on an uninitialized object.

preferencesItem = [[NSMenuItem alloc] initWithTitle:@"Preferences…" action:@selector(showPreferencesPanel) keyEquivalent:@""];
[preferencesItem setTarget:kbAppController]

Upvotes: 1

Legolas
Legolas

Reputation: 12345

Have the selector call the method from your class. And inside that method, call showPreferencePanel() with the object of KBAPPController .

Make sure to set the object of KBAppController as a property of StatusMenu.

Upvotes: 0

Related Questions