是否可以使C++类成为Objc类的委托
Is it possible to make a C++ class be the delegate of Objc class?
因为我需要继承一些在C++中声明为超类的处理程序,所以我必须将我的类声明为C++
类。但我也想让它成为两个Objective-C
类的委托。在我的C++类中使用委托模式是不可避免的,但我不知道如何使C++类成为Objective-C类的委托。
有可能吗?或者有间接的方法吗?
这里有一个快速而肮脏的例子。
需要委托给C++的Objective-C类的接口和实现:
@interface MyClassOC : NSObject
@property id<MyDelegateProtocol> myDelegate;
-(void)doStuff;
@end
@implementation MyClassOC
-(void)doStuff {
if (self.myDelegate) {
[self.myDelegate performOperation];
}
}
@end
MyDelegateProtocol
是
@protocol MyDelegateProtocol
-(void)performOperation;
@end
要用作委托的C++类:
class MyDelegateCPP {
public:
void performOperation();
};
void MyDelegateCPP::performOperation() {
cout << "C++ delegate at work!n";
}
MyClassOC
不能直接使用MyDelegateCPP
,所以我们需要将C++类封装在可以使用C++并且可以由Objective-C类使用的东西中。Objective-C++拯救!
包装类:
@interface MyDelegateOCPP : NSObject <MyDelegateProtocol>
-(void)performOperation;
@end
// This needs to be in a .mm (Objective-C++) file; create a normal
// Objective-C file (.m) and change its extension to .mm, which will
// allow you to use C++ code in it.
@implementation MyDelegateOCPP {
MyDelegateCPP * delegateCPP;
}
-(id)init {
delegateCPP = new MyDelegateCPP();
return self;
}
-(void)performOperation {
delegateCPP->performOperation();
}
@end
这可以如下使用:
MyDelegateOCPP * delegate = [[MyDelegateOCPP alloc] init];
MyClassOC * classOC = [[MyClassOC alloc] init];
classOC.myDelegate = delegate;
[classOC doStuff];
同样,这只是一个过于简单化的草图,但希望它能给你一个想法。
您需要知道委托是Objective-C中的返回数据。如果您使用C++语言将类创建为超级类,它将返回数据。让我们来做吧。
首先,您使用C++语言,这意味着创建C++类,然后添加objective-C类。所以C++类和objc类混合在一个xxx.h/xxxx.mm中。
其次,您还需要委托,您只在其他objc类中使用objc实现。
请参阅测试代码。
TestViewController.h
#import <UIKit/UIKit.h>
class testC
{
public:
static int useCMethod();
};
@protocol helloCDelegate<NSObject>
@optional
- (void)testDelegateTransformDataInTest:(int)testNum;
@end
@interface TestViewController : UIViewController
@property (nonatomic,weak) id<helloCDelegate> delegate;
@end
TestViewController.mm -- section operate implement code
int testC::useCMethod(){
return 3;
}
// you can use C++ method and C++ object in sample method.
// also it use delegate in here,so you can implement in other view controller.
- (void)tapBackTranformReturnData
{
int num = testC::useCMethod();
[self.delegate testDelegateTransformDataInTest:num];
}
哦,最重要的一点是必须将xxx.m
文件更改为xxx.mm
。这意味着Objective-C++可以使用C++语言和Objective-C。
你需要这个功能吗?我希望能帮助你。
相关文章:
- 是否可以使C++类成为Objc类的委托
- 是否可以使一个类成为两个不同层次结构的子类?
- 是否有编译器标志可以使较新的 gcc 版本像旧版本一样构建
- C 可以使destuructor不称为班级成员和基类攻击方的灾难
- 可以使未命名的结构静态
- 是否可以使整数仅收到一个单个数字而不是两个接收输入
- C++:有哪些常规方法可以使代码更有效地用于大数字
- 是否可以使 std 容器使用默认运算符为新?
- LD_BIND_NOW可以使可执行文件运行得更慢?
- 是否可以使头文件使文本居中?- 在控制台中
- 有什么方法可以使核心忙碌等待
- 有没有一种技术可以使虚函数在所有派生类中强制重写?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 是否有一种方法可以使此C 14递归模板在C 17中短
- 编写一个可以使二维数组平坦的函数
- 有哪些优化技巧可以使我的代码运行得更快
- 有没有更好的方法可以使此代码线程安全?线程局部静态似乎是一个生硬的工具
- 如果必须在同一向量上写入线程,是否可以使用线程
- 对于具有两个模板化变量的模板化类,是否可以使一个 var 引用另一个 var
- C 中的内容可以使Windows 8应用程序不在手臂上运行