我的联系人侦听器代码中出现EXC_BAD_ACCESS错误。以下是代码:
主对象类(GameObjects),所有对象都通过它们进行子类化:
GameObjects.h:
#import "cocos2d.h"
#import "CCNode.h"
#import "CCPhysicsSprite.h"
#import "Box2D.h"
#include <math.h>
@interface GameObjects : CCNode {
//b2Body* objectBody_;
}
-(b2Body*)getObjectBody;
-(void)objectsTouched:(GameObjects*)otherObject;
@end
GameObjects.mm(现在我只想让CCLOG判断它是否正常工作):
#import "GameObjects.h"
@implementation GameObjects
-(b2Body*)getObjectBody {
}
-(void)objectsTouched:(GameObjects*)otherObject {
CCLOG(@"it's working");
}
@end
ContactListenerTest.h:
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "Box2D.h"
#import "Enemy.h"
#import "Sprite.h"
#import "GameObjects.h"
class ContactListenerTest : public b2ContactListener {
public:
b2World* world;
void BeginContact(b2Contact* contact);
};
ContactListenerTest.mm:
#import "ContactListenerTest.h"
void ContactListenerTest:: BeginContact(b2Contact *contact)
{
b2Fixture *fixtureA = contact->GetFixtureA();
b2Fixture *fixtureB = contact->GetFixtureB();
b2Body *fixtureABody = fixtureA->GetBody();
b2Body *fixtureBBody = fixtureB->GetBody();
GameObjects* spriteObject = (GameObjects*)fixtureABody->GetUserData();
GameObjects* spriteObject2 = (GameObjects*)fixtureBBody->GetUserData();
[spriteObject objectsTouched:spriteObject2];
[spriteObject2 objectsTouched:spriteObject];
}
当我收到EXC_BAD_ACCESS错误时,控制台中会打印以下内容:
-[Enemy objectsTouched:]: unrecognized selector sent to instance 0x8558840
Enemy是GameObjects的子类之一。
答案 0 :(得分:1)
验证userdata对象实际上是GameObjects类:
NSAssert1([spriteObject isKindOfClass:[GameObjects class]],
@"userdata %@ not a game object", spriteObject);
NSAssert1([spriteObject2 isKindOfClass:[GameObjects class]],
@"userdata 2 %@ not a game object", spriteObject2);
答案 1 :(得分:0)
初始化GameObject时,应确保创建的主体的UserData指向GameObject。像这样:
objectBody_->SetUserData(self);