Search code examples
objective-cnslogobjective-c-runtime

Objective C: Method have knowledge of context within which it was called?


I'd like to have a reusable logging method or function that spits out the name of the method it's called from. Example:

    - (void)exampleMethod {
        CustomLog(); //Outputs "exampleMethod"
    }

Solution

  • Functions don't know about their calling environment (at least not in a useful way). The only way is to use a macro instead. Inside the macro, you have access to the self and _cmd arguments that hold the receiver and current selector, as well as the __PRETTY_FUNCTION__ macro that contains the human-readable name of the method as a C string.