How to stop listening to NSEvents?

I have a problem listening to events, I can listen to events that work fine, but I can not get it to stop listening to events. I researched it for a while and came up with the + (void) removeMonitor: (id) eventMonitor method, which says what should I use when I am done with the listener

But when I try to use a method, sort of like

[NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDownMask|NSKeyDownMask) handler:^(NSEvent *event) {
    [NSEvent removeMonitor:event];
}];

I keep getting the error message “[NSEvent invalidate]: unrecognized selector sent to the instance.” What I also studied, and I believe that this means that I am overwriting the used memory. ”However, I do not know how to solve this problem. Any suggestions or help are welcome!

UPDATE Thanks to JWWalker, Samir and Abizern, it now works

//I made a global variable called eventHAndler

.h file

id eventHAndler

.m file

eventHAndler = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDownMask|NSKeyDownMask) handler:^(NSEvent *event){
///code 
}];

/// created another method called stop. When called it stops the eventHAndler
- (IBAction)Stop:(id)sender 
{
    stop = 1;
    NSLog(@"inside stop method");
    [NSEvent removeMonitor:eventHAndler];
}
+5
2

removeMonitor:. +[NSEvent addGlobalMonitorForEventsMatchingMask: handler:] , . removeMonitor:.

+12

All Articles