What is the correct way to call IBAction from different controller?
It's about objective c and cocoa
I've faced a problem and don't know how to solve it. Hope I can find answer here and it will be helpful for some other programmers.
So, I have a simple window with 4 elements:
- NSTextField - first field to set value
- NSButton - to set value in first field
- NSTextField - second field to set value
- NSButton - to set value in second field
here is "controller 1" code:
#import "controller2.h"
@interface controller1 : NSControl{
IBOutlet NSTextField * text1;
}
-(IBAction)click:(id)sender;
@end
@implementation controller1
-(IBAction)click:(id)sender
{
[text1 setStringValue:@"text1 changed"];
// create controller 2 instance
controller2 * c2 = [[[controller2 alloc] init] autorelease];
// call first time using one way
[c2 click:self];
// call second time using another way
[self sendAction:@selector(click:) to:c2];
}
@end
and controller 2 code:
@interface controller2 : NSControl{
IBOutlet NSTextField * text2;
}
-(IBAction)click:(id)sender;
@end
@implementation controller2
-(IBAction)click:(id)sender
{
[text2 setStringValue:@"text 2 changed"];
NSLog(@"Test2");
}
@end
when I click on button1 I rase "click" in controller1 - everything is fine and work correct
when I click on button2 I rase "click" in controller2 - everything is fine and work correct
开发者_开发知识库BUT if I want to click button1 and rase "click" in controller2 it doesn't work (
Can anyone help with it? It seems to have a very simple resolution but i don't know what i did wrong.
controller2 * c2 = [[[controller2 alloc] init] autorelease];
You're creating a completely new "controller2" (bad name for a class, by the way - always capitalize class names: "MyController", etc.). You need an IBOutlet from your Controller1 to a Controller2. That way you can send messages to it by name.
Remember: objects in a nib are "freeze-dried" instances of classes.
精彩评论