要在iOS上创建音频单元扩展,需要混合使用C ++和Objective-C类。结果,我现在有了一个带有C ++对象作为其变量之一的Objective-C对象。

我希望C ++子对象能够将某些状态更改通知其Objective-C父/所有者。

用伪代码:

void cppChildObject::callMom() {
   objectiveCParent::notificationMethod();
}


这有可能优雅吗?

最佳答案

这取决于定义优雅的方式...如果C ++类位于Objective-C ++文件(扩展名为.mm的文件)中,并且未由非C ++代码直接使用的C ++代码,则可以用相当优雅的方式实现Objective-C ++源文件。问题是C ++代码只有在Objective-C ++源文件中才能使用Objective-C类型。这是一个简单的示例,希望对您有所帮助。

Objective-C ++文件mylib.mm(注意.mm扩展名):

#import "objcpp.h"
#import <stdio.h>
#import "cpp.h"

// A C++ class in an Objective-C++ file.
// This C++ class would not need to sub-class ParentNotifier, and ParentNotifier
// would not be needed at all if it were not for OutsiderCPP, which talks to its
// Objective-C parent through InsiderCPP.
class InsiderCPP : public ParentNotifie {
public:
    InsiderCPP(MyClassOCPP * parent) : myParent(parent){}
    void doSomething() {
        callMom("To Mom from insider.");
    }
    void callMom(const char * msg) {
        [myParent notificationMethod:msg];
    }
private:
    MyClassOCPP * __weak myParent;
};

@interface MyClassOCPP ()

@property InsiderCPP * insiderChild;
@property OutsiderCPP * outsiderChild;

@end

@implementation MyClassOCPP
-(id)init {
    self.insiderChild = new InsiderCPP(self);
    self.outsiderChild = new OutsiderCPP(self.insiderChild);
    return self;
}
-(void)doWork {
    self.insiderChild->doSomething();
    self.outsiderChild->doSomething();
}
-(void)notificationMethod:(const char *)msg {
    printf("Parent has been notified with: %s\n", msg);
}
-(void)dealloc {
    delete self.insiderChild;
    delete self.outsiderChild;
}
@end


这是对应的标题objcpp.h

#ifndef objcpp_h
#define objcpp_h

#import <Foundation/Foundation.h>

@interface MyClassOCPP : NSObject
-(id)init;
-(void)dealloc;
-(void)doWork;
-(void)notificationMethod:(const char*)msg;
@end

#endif


这是与Objective-C无关的“纯” C ++源文件(mylib.cpp):

#include <stdio.h>
#include "cpp.h"

void OutsiderCPP::callMom(const char * m) {
    myParent->callMom(m);
}
void OutsiderCPP::doSomething() {
    callMom("To Mom from outsider.");
}


这是对应的标头(cpp.h):

#ifndef cpp_h
#define cpp_h

class ParentNotifier
{
public:
    virtual void callMom(const char *) = 0;
};

class OutsiderCPP
{
public:
    OutsiderCPP(ParentNotifier * p) : myParent(p) {}
    void doSomething();
    void callMom(const char *);

private:
    ParentNotifier * myParent;
};

#endif


请注意,此示例仅用于说明目的,并非生产质量。

09-30 15:47
查看更多