从 C++ 调用 Objective-C 方法使用模板和命令模式
我在 stackoverflow 上找不到它。我想出了这个方法。请建议是否有更好的方法。
代码:
C++类:
struct CmdObj{
int value;
...
};
class CallBack{
public:
virtual void operator()(CmdObject &cmdObj) = 0;
};
#ifdef __OBJC__
//For objective c class
template <class T>
class CallBackImpl: public CallBack{
public:
CallBackImpl(T* _object, SEL _method): object(_object), method(_method){}
virtual void operator()(CmdObject &cmdObj){
NSValue *anObj = [NSValue value:&cmdObj withObjCType:@encode(CmdObject)];
[object performSelector:method withObject:anObj];
}
private:
SEL method;
T* object;
};
#endif
该类在Objective C中的使用:
@interface Callee{
CallBack *delegate;
}
- (void) callbackMethod:(NSValue *) anObj;
@end
@implementation
- (id) initCallee{
delegate = new CallBackImpl<Callee>(self, @selector(callbackMethod:);
}
- (void) callbackMethod:(NSValue *) anObj
{
CmdObject cmdObj;
[anObj getValue:&cmdObj];
int value = cmdObj.value;
...
}
- (void) callDelegate: (NSInteger _value)
{
if(delegate == NULL ) return;
CmdObject cmdObj;
cmdObj.value = _value;
(*delegate)(cmdObj);
}
@end
I was not able to find it on stackoverflow. I have come up with this approach. Please suggest if there is any better way to do it.
Code:
The C++ class:
struct CmdObj{
int value;
...
};
class CallBack{
public:
virtual void operator()(CmdObject &cmdObj) = 0;
};
#ifdef __OBJC__
//For objective c class
template <class T>
class CallBackImpl: public CallBack{
public:
CallBackImpl(T* _object, SEL _method): object(_object), method(_method){}
virtual void operator()(CmdObject &cmdObj){
NSValue *anObj = [NSValue value:&cmdObj withObjCType:@encode(CmdObject)];
[object performSelector:method withObject:anObj];
}
private:
SEL method;
T* object;
};
#endif
The use of this class in Objective C:
@interface Callee{
CallBack *delegate;
}
- (void) callbackMethod:(NSValue *) anObj;
@end
@implementation
- (id) initCallee{
delegate = new CallBackImpl<Callee>(self, @selector(callbackMethod:);
}
- (void) callbackMethod:(NSValue *) anObj
{
CmdObject cmdObj;
[anObj getValue:&cmdObj];
int value = cmdObj.value;
...
}
- (void) callDelegate: (NSInteger _value)
{
if(delegate == NULL ) return;
CmdObject cmdObj;
cmdObj.value = _value;
(*delegate)(cmdObj);
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论