views:

27

answers:

2

In Objective-C, is it possible to access instance variables and methods from within the scope of a static c function? I feel like there is probably a simple answer to this that I'm overlooking, but I'm still fairly new to this language.

Consider the following stripped down code:

@implementation MyObject

static int ammoHitSensor(cpArbiter *arb, cpSpace *space, void *unused)
{
    // Call an instance method - doesn't work, self is undefined!
    [self doSomethingElse];
}

-(id)init
{
    // Code to create graphics, etc, hidden for clarity 
    // Adding a collision handler in the Chipmunk physics library
    cpSpaceAddCollisionHandler(space, COL_TYPE_AMMO, COL_TYPE_SENSOR, ammoHitSensor, NULL, NULL, NULL, NULL);
}

-(void)doSomethingElse
{
    // Stuff happens
}

@end

So I guess once I get into the scope of ammoHitSensor, I'm hoping there is some way to get back into the scope of MyObject. So far I haven't had any luck.

+2  A: 

You need to pass self along when you call that C function. C functions don't have self or _cmd since they don't live inside objects (regardless of where you put them in your code).

jer
Aha, that did the trick. Thanks!
Greg W
+1  A: 

Try this:

static int ammoHitSensor(cpArbiter *arb, cpSpace *space, void *obj)
{
    [(MyObject*)obj doSomethingElse];
}

-(id)init
{
    cpSpaceAddCollisionHandler(space, COL_TYPE_AMMO, COL_TYPE_SENSOR, ammoHitSensor, NULL, NULL, NULL, self);
}
Aleph