I want to listen to some ofEvents from an objective C class. It has to be an objective C class since it inherits from UIViewController and displays native iOS views.
I had problems with giving an objective C method as the target, since the signatures don’t match.
After some investigating (and googling), I found a scheme that works. I made a cpp class to use as an adapter:
It works. But that’s allot of pipework just to call one event, and it’s not scalable.
I was thinking of making a generic adapter template method that will hold a pointer to the objective C selector and will call it, but I’m not sure if it’s needed or even doable…
I would love some opinions before I give this a shot…
No takers on this? Well, I went ahead and made a working version of a the handler, and here it is:
template <typename ArgumentsType>
class ofEventAdapter {
ofEvent<ArgumentsType>& m_ofEvent;
id m_targetInstance;
SEL m_targetSelector;
public:
ofEventAdapter(ofEvent<ArgumentsType>& ofEvent, id targetInstance, SEL targetSelector):
m_ofEvent(ofEvent),
m_targetInstance(targetInstance),
m_targetSelector(targetSelector)
{
ofAddListener(m_ofEvent, this, &ofEventAdapter<ArgumentsType>::eventCallback);
}
ofEventAdapter()
{
ofRemoveListener(m_ofEvent, this, &ofEventAdapter::eventCallback);
}
void eventCallback(ArgumentsType& args)
{
if (![m_targetInstance respondsToSelector:m_targetSelector])
{
return; //can't call selector!
}
[m_targetInstance performSelector:m_targetSelector withObject:(id)(&args)];
}
};
Usage:
ofEventAdapter<[AnyType]>
([ofEvent from the corresponding type], self, @selector([your objectiveC callback method]]))
It reduced my boilerplate code drastically, but it can still be improved. I envision it as being two static methods, like the original ofAddListener/ofRemoveListener, but that will require a template method, and for each type, it will need to go to a different map of events to targets, and I don’t have the time to set such a thing up right now.