How does an NSView subclass communicate with the controller?

Viewed 6841

I am brand spanking new to Cocoa programming, and am still kind of confused about how things wire together.

I need a pretty simple application that will fire off a single command (let's call it DoStuff) whenever any point on the window is clicked. After a bit of research it looks like subclassing NSView is the right way to go. My ClickerView.m file has this:

- (void)mouseDown:(NSEvent *)theEvent {
    NSLog(@"mouse down");
}

And I have added the View to the Window and have it stretching across the whole thing, and is properly writing to the log every time the window is clicked.

I also have my doStuff method on my controller (this could be refactored to its own class I suppose, but for now it works):

- (IBAction)doStuff:(id)sender {
    // do stuff here
}

So, how do I get mouseDown in ClickerView to be able to call DoStuff in the controller? I have a strong .NET background and with that, I'd just have a custom event in the ClickerView that the Controller would consume; I just don't know how to do that in Cocoa.

edit based on Joshua Nozzi's advice

I added an IBOutlet to my View (and changed it to subclass NSControl):

@interface ClickerView : NSControl {
    IBOutlet BoothController *controller;
}
@end

I wired my controller to it by clicking and dragging from the controller item in the Outlets panel on the View to the controller. My mouseDown method now looks like:

- (void)mouseDown:(NSEvent *)theEvent {
    NSLog(@"mouse down");
    [controller start:self];
}

But the controller isn't instantiated, the debugger lists it as 0x0, and the message isn't sent.

3 Answers

you can also use a selector calling method, define two properties in custom class:

@property id parent;
@property SEL selector;

set them in view controller:

graph.selector=@selector(onCalcRate:);
graph.parent=self;

and call as:

-(void)mouseDown:(NSEvent *)theEvent {
    [super mouseDown:theEvent];
    [_parent performSelector:_selector withObject:self];
}
Related