Calling Cocoa IBAction from Carbon Code
I'm trying to call a Cocoa IBAction
from Carbon code...
I've set up global keys using this tutorial.
The hot keys are working fine, but I need to fire an IBAction when the global key has been pressed.
I keep getting errors when I use
[self functionName]
How do I call the function?
I've r开发者_如何学运维ead about passing the Cocoa controller to the carbon method. How would I do this? or what is the best way?
I assume you're calling [self functionName]
in a Carbon Event handler callback. That's not an Objective-C method, so of course self
is not defined.
When you install a Carbon Event handler, one of the parameters is a "user data" pointer. You can pass an Objective-C object pointer in this parameter, so that your event handler will get it, and you can say something like [(MyController*) inUserData functionName]
. Of course, to make this work, your handler must be in an Objective-C or Objective-C++ source file.
you can pass one of these as your user data while keeping the program safe for c++ translations:
/* include the necessary C header, located in objc/ (objc/objc.h?) */
/* of course, definitions with objc messaging belong in your .mm file */
class t_ibaction_invocation {
/* you may want to retain d_target or d_optionalArgument, and release at destruction */
enum { RetainArguments = 0 };
public:
/* IBAction takes the form: [target action:optionalArgument]; */
t_ibaction_invocation(id target, SEL action, id optionalArgument) : d_target(target), d_action(action), d_optionalArgument(optionalArgument) {
assert(this->d_target);
if (RetainArguments) {
[this->d_target retain];
[this->d_optionalArgument retain];
}
}
~t_ibaction_invocation() {
if (RetainArguments) {
[this->d_target release], target = 0;
[this->d_optionalArgument release], optionalArgument = 0;
}
}
id performAction() {
if (this->d_target && this->d_action) {
return [this->d_target performSelector:this->d_action withObject:this->d_optionalArgument];
}
else {
assert(d_target && d_action);
return 0;
}
}
private:
id d_target;
SEL d_action;
id d_optionalArgument;
};
精彩评论