问题
I have a C function(a callback function in Audio Queue Services) and I want to send message to self. How to do that? If I type in [self message], there is an error:
Use of undeclared identifier 'self'
回答1:
You don't perform objc messages in realtime callbacks, such as audio. The reason for this is that objc messaging is not constant time, and may lock, resulting in missed deadlines, resulting in audio dropouts. Static or dynamic (virtual
) C++ calls and C function calls are of course constant time, and suitable for realtime contexts.
If it were not an realtime/audio callback, then one option would be to pass self
as the user info or context parameter:
void SomeCallback(t_stuff* const stuff, void* userInfo) {
MONClass * Self = (MONClass*)userInfo;
[Self doSomething];
}
回答2:
self
is only meaningful in the context of a class definition -- it's a pointer to an instance of that class. Functions aren't part of any class, so there is no self
pointer. If you want your callback to be able to send a message to a given object, you'll need to stash a pointer to that object where your callback can find it. That might be a global variable (ick), a userInfo
parameter that's meant for just this sort of thing (much better), or somewhere else.
来源:https://stackoverflow.com/questions/10378629/how-to-send-a-message-to-self-in-a-c-function-in-obj-c