Search code examples
objective-cibaction

Callback method can't invoke IBAction - iPhone


I have a button linked to an IBAction, which plays a sound with AudioServices. That AudioServicePlaySystemSound is linked with

AudioServicesAddSystemSoundCompletion(silenceID, NULL, NULL, callbackFunction, (__bridge void*) self);

Nevertheless, inside CallbackFunction I can't invoke the IBAction method. In fact, I can't even use the reserved work self. I found out that it may be because C itself doesn't know what self is.

Thanks.


Solution

  • You cannot access pointers such as self from within a C function. This is because the function is not actually part of the class. To call a method on self you need to provide some way to access the pointer self from the C function.

    Luckily the callbackFunction accepts two arguments, the first is the sound id, and the second is data you provide in the AudioServicesAddSystemSoundCompletion function. (__bridge void*) self

    void callbackFunction(SystemSoundID sound, void *data){
        //data is a pointer to self that you provide when you call AudioServicesAddSystemSoundCompletion
        [(MyClass*)data callMyIBAction];
    }