objective-cself

How to call an Objective-C Method from a C Method?


I have an Obj-C object with a bunch of methods inside of it. Sometimes a method needs to call another method inside the same object. I can't seem to figure out how to get a C method to call a Obj-C method...

WORKS: Obj-C method calling an Obj-C method:

[self objCMethod];

WORKS: Obj-C method calling a C method:

cMethod();

DOESN'T WORK: C method calling an Obj-C method:

[self objCMethod];     // <--- this does not work

The last example causes the compiler spits out this error:

error: 'self' undeclared (first use in this function)

Two questions. Why can't the C function see the "self" variable even though it's inside of the "self" object, and how do I call it without causing the error? Much thanks for any help! :)


Solution

  • In order for that to work, you should define the C method like this:

    void cMethod(id param);
    

    and when you call it, call it like this:

    cMethod(self);
    

    then, you would be able to write:

    [param objcMethod];
    

    In your cMethod.

    This is because the self variable is a special parameter passed to Objective-C methods automatically. Since C methods don't enjoy this privilege, if you want to use self you have to send it yourself.

    See more in the Method Implementation section of the programming guide.