iOS class property not accessible in CFSocketCallback

641 views Asked by At

I have a CFSocket callback method that is declared like this:

void socketCallback(CFSocketRef cfSocket, CFSocketCallBackType type, CFDataRef address, const void *data, void *userInfo)
{
    if (_scanningInProgress) {

    }
}

And the problem is that I get an "Use of undeclared identifier '_scanningInProgress' error. I am a little confused because if I try something like this:

-(void)scan:(bool)isScanning
{
    _scanningInProgress = isScanning;
}

Then everything is working just fine. What is causing the error? Here is the .h file declaration for the property:

@property bool scanningInProgress;
1

There are 1 answers

1
Droppy On BEST ANSWER

The issue is that you are using a C API from within Objective-C and any callback functionality requires some info passed to it in order for the callback function to make sense of the context it's been called in. In your case you need to pass the Objective-C object reference in the CFSocketContext structure and access it from the info parameter (the last one):

When creating the socket:

const CFSocketContext context = { 0, self, NULL, NULL, NULL };
socket = CFSocketCreateWithNative(NULL, sock, kCFSocketReadCallBack,
                                  socketCallback, &context);

and access it within the callback method:

void socketCallback(CFSocketRef cfSocket, CFSocketCallBackType type,
                    CFDataRef address, const void *data, void *info)
{
    YourObject *obj = (YourObject *)info;
    if (obj.scanningInProgress) {

    }
}

(It's possible you might need some bridging directives in for this to compile without errors or warnings; I'm not in a position to test it at the time of writing).