Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop listening for NSEvents?

I have a problem with listening for events, I can listen for events which works perfectly however I can't make it stop listening to events. I researched it for a while and came up with the a method, + (void)removeMonitor:(id)eventMonitor, that it says I should use when I'm done with the listener

But when I try to use the method, like so

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

I keep getting an error of "-[NSEvent invalidate]: unrecognized selector sent to instance" Which I researched as well, and I believe it means that I'm overwriting a memory that is being used. However I don't know how to solve this problem. Any suggestions, or help is greatly appreciated!

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];
}
like image 451
A.sharif Avatar asked Aug 19 '12 23:08

A.sharif


1 Answers

You're passing the wrong thing to removeMonitor:. The call to +[NSEvent addGlobalMonitorForEventsMatchingMask: handler:] returns a value called an event handler object. That's what can be passed to removeMonitor:.

like image 54
JWWalker Avatar answered Oct 19 '22 11:10

JWWalker