开发者

Saving a subclass of NSObject in Box2d UserData and retrieve it back?

I have a game entity class as follows :

@interface CPlanet : NSObject {
    b2Body *planetBody;
}

-(void)init;
-(void)syncWithPhysics;

@end

in the init() method I create a b2Body instance and assign the CPlanet instance to its userdata ,as follows :

//creating the physics
b2BodyDef bodyDef;
bodyDef.type=b2_dynamicBody;
bodyDef.userData=self;
planetBody=world->CreateBody(&bodyDef);

In my CCLayer instance, I try to retrieve this object as follows :

for(b2Body* b =world->GetBodyList();b;b=b->GetNext())
{
    void *uda开发者_运维问答ta=b->GetUserData();
    if(udata!=NULL)
    {
       CCLOG(@"Some udata %d",udata);
       CPlanet *planet=(CPlanet*)udata;
       // [planet syncWithPhysics];   <---- here programm crashes ???

     }
}

But the line "[planet syncWithPhysics]" crash the application with error

Program received signal: “EXC_BAD_ACCESS”.

I checked the memory address of retrieved CPlanet instance (udate) is the same object.

Any tips? Does this has to do Box2D being C++ and I use Objective-C instance?


The planet object has been deallocated at the time you dereference the pointer. You'll have to retain the object!

You could make the planet a CCNode object and add it as child to the layer. Then it will be retained by the layer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜