gpt4 book ai didi

c++ - 从 cpp 方法调用 objective-c 方法

转载 作者:行者123 更新时间:2023-11-30 04:38:02 26 4
gpt4 key购买 nike

我有一个这样的 cpp 类..

class MyContactListener : public b2ContactListener
{
int countContact;
///this is an objective c class...
HelloWorld *hel;


public:
void EndContact(b2Contact* contact)
{
///initialize objective c object
hel=[[HelloWorld alloc] autorelease];
///call objective c method.........
[hel beginContact];

}

};

在 cpp 类中我调用了一个 objective c 方法。objective c 方法看起来像..

-(void )beginContact
{
shakeCounter++;
[_label setString:[NSString stringWithFormat:@"%d",shakeCounter]];


}

objective c 方法被调用....并且变量 shakeCounter 也增加了......但是_label 字符串未更新...._label 已正确初始化并且如果我调用则可以正常工作objective c 类的 objective c 方法使用 self....

谁能帮忙???

最佳答案

在 Contact 监听器中使用 Delegate 来调用 objective-c 类的方法:

class MyContactListener : public b2ContactListener
{
public:
MyDelegateClass *delegate;

void BeginContact(b2Contact* contact) {
[delegate beginContact:contact];
}

void EndContact(b2Contact* contact) {
[delegate endContact:contact];
}

void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) {
[delegate preSolve:contact manifold:oldManifold];
}

void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) {
[delegate postSolve:contact impulse:impulse];
}
};

为委托(delegate)声明一个协议(protocol):

#import "Box2D.h"

@protocol B2ContactListener <NSObject>

-(void) beginContact:(b2Contact*) contact;
-(void) endContact:(b2Contact*) contact;
-(void) preSolve:(b2Contact*) contact manifold:(const b2Manifold*) oldManifold;
-(void) postSolve:(b2Contact*) contact impulse:(const b2ContactImpulse*) impulse;

@end

声明实现协议(protocol)的接口(interface):

@interface MyDelegateClass: CCLayer <B2ContactListener> {
//interface code here.
}
@end

@implementation MyDelegateClass

-(void) beginContact:(b2Contact*) contact {
//implement your code here
}
-(void) endContact:(b2Contact*) contact {
//implement your code here
}
-(void) preSolve:(b2Contact*) contact manifold:(const b2Manifold*) oldManifold{
//implement your code here
}
-(void) postSolve:(b2Contact*) contact impulse:(const b2ContactImpulse*) impulse{
//implement your code here
}
@end

构造委托(delegate)并在您的代码中分配它。将它设置在你的世界对象中:

MyContactListener *listener = new MyContactListener();
listener->delegate = self;
world_->SetContactListener(listener);

现在您的 objective-c 类将接收事件。

关于c++ - 从 cpp 方法调用 objective-c 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3403907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com