r/macosprogramming • • Apr 27 '24

`mouseEntered` in NSViewController?

Hello, might be a stupid question, but I'm not able to have an NSViewController be notified of mouseEntered events. This is inside the ViewController class:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:[self.view bounds]
        options: (NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect)
        owner:self userInfo:nil];
    [self.view addTrackingArea:trackingArea];
}

- (void)mouseEntered:(NSEvent *)theEvent {
    NSLog(@"Mouse entered");
}

- (void)mouseExited:(NSEvent *)theEvent {

}

This is mostly taken from: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/TrackingAreaObjects/TrackingAreaObjects.html

As you can see, I provide owner as self (which is the ViewController), but add trackingArea to self.view. mouseEntered is never called. Does anyone know why?

1 Upvotes

2 comments sorted by

View all comments

Show parent comment

2

u/Devirichu Apr 28 '24

Thanks, that got me on the right track! I think it was because of the deallocation, as my (sub)view controller was declared in a weak property.