是否可以使C++类成为Objc类的委托

Is it possible to make a C++ class be the delegate of Objc class?

本文关键字:Objc 可以使 C++ 是否      更新时间:2023-10-16

因为我需要继承一些在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。

你需要这个功能吗?我希望能帮助你。