Pieter Beulque
Pieter Beulque

Reputation: 191

setAction: in NSViewController

It might be helpful to know that I come from a iOS background and that this is one of my first OS X projects.

In my project, I have a NSView subclass and a NSViewController and load the view in the controller.

- (void)loadView
{
    StartView *view = [StartView alloc] initWithFrame:frame]; // frame exists
    self.view = view;
}

The view has a NSButton-property btnNewthat I add in initWithFrame:.

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.btnNew = [[NSButton alloc] initWithFrame:NSRectFromCGRect(CGRectMake(350, 180, 300, 60))];

        [self addSubview:self.btnNew];
    }

    return self;
}

In loadView: I try to set the action and target.

- (void)loadView
{
    StartView *view = [StartView alloc] initWithFrame:frame]; // frame exists

    [view.btnNew setTarget:self];
    [view.btnNew setAction:@selector(createNew:)];

    self.view = view;
}

The createNew: function exists, off course.

However, when clicking the button, the app crashes. When I move the setTarget: and the setAction: into the view and perform them on self.btnNew, it works, but I think that's not how you should work with events and user interaction in a decent MVC-architecture.

The problem is with the self in [view.btnNew setTarget:self];, I guess. If I grab the target with view.btnNew.target, this is a nil object (0x000…000). Self exists & view.btnNew exists.

Am I doing something wrong? Or should I really listen to the click in the view and work with a delegate or a notification (I guess not?)

Upvotes: 2

Views: 387

Answers (1)

Pieter Beulque
Pieter Beulque

Reputation: 191

I found it out myself, with help from Niel Deckx.

The problem was ARC. The ViewController got dealloced before the click happened, which explains the NSObject does not respond to selector: the target doesn't exist anymore.

The easy solution is to have the ViewController as a (strong?) property where you create it.

Upvotes: 2

Related Questions