Safe to use matching CFBridging calls to transfer in and out of ARC for non CF types?

325 views Asked by At

I'm writing a game using the Chipmunk physics engine, and I'd like to store a pointer to an Objective-C object in every body's userData field. I know I need to use a bridging cast to cast between id and void *, but I'm not sure the way I'm doing it is safe:

// When body is created
cpBody *body = cpBodyNew(...);
UserData *userData = [[UserData alloc] init];
cpBodySetUserData(body, CFBridgingRetain(body));

...

// When body is destroyed
UserData *userData = cpBodyGetUserData(body);
CFBridgingRelease(userData);
cpBodyFree(body);

This code seems to work, but I've also read that you're only supposed to use CFBridging*() on objects that can be toll-free bridged to Core Foundation types. Since UserData is derived from NSObject, and NSObject isn't on the list of toll-free bridged types, I seem to be breaking that rule.

Is my code okay because I eventually call CFBridgingRelease and don't try to pass the object to any other Core Foundation functions, or is there another way I should be going about transferring Objective-C objects in and out of C?

1

There are 1 answers

4
Ken Thomases On BEST ANSWER

It's safe. NSObject is toll-free bridged to a generic CFTypeRef. Also, I'm assuming you aren't calling any other Core Foundation functions on the void*, so it hardly matters.