Logging class and method names in Objective-C

Today I was debugging a tricky problem in an iOS app that only happened when I was not using the debugger. Due to some strange timing issue (that I have yet to figure out), stopping on breakpoints actually caused the problem to go away, no matter how quickly I clicked the debugger’s continue button. So how was I to find out what was wrong?

I decided that printing the name of the class and method that was being called might be a good idea. So I started with this naïve approach:

- (void)viewDidLoad
{
    NSLog(@"MyViewController viewDidLoad");
    // ...
}

Of course, adding this to each method that I wanted to debug was quickly going to get out of hand. I didn’t want to have to change the class name and method name in the string each time I copied and pasted my NSLog statement. So I went searching for a solution, came across this Stack Overflow question about logging Objective-C method names, and took a good long look at the accepted answer, which said to use this:

NSLog(@"%s" , _cmd);

But after reading the comments, looking over Apple’s Technical Q&A on the topic, and learning that the compiler flags that statement with a warning, I decided I didn’t like that approach. Since _cmd is defined as a SEL, Apple says to use it with NSStringFromSelector, like this:

NSLog(@"%@", NSStringFromSelector(_cmd));

This fixes the compiler warning, but now it doesn’t output what I want. Here’s what it spits out in the console:

viewDidLoad

Umm…yeah…not very useful. No class information. So it’s not at all helpful if I’m trying to see which class’s viewDidLoad was called. Moving further through the Technical Q&A (and the highest-voted Stack Overflow answer), I found…

The Best Way to Log Class and Method Names in Objective-C

NSLog(@"%s", __PRETTY_FUNCTION__);

…which when placed into a viewDidLoad like so…

- (void)viewDidLoad
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    // ...
}

…produces some lovely output in our console like this…

-[MyViewController viewDidLoad]

…which is exactly what I wanted.

So the PRETTY_FUNCTION preprocessor macro prints the class name, method name, and indicates whether it’s a class method or an instance method (for an added bonus!). And for a second added bonus, it’s easy to remember. Much easier than _cmd…

And there you have it – you can easily copy and paste this into each method you want to log without changing anything inside the NSLog statement.

Enter your email below and grab my advice, tips, and tutorials on iOS development designed to help you become a master of iOS development – and never worry about whether your iOS chops are getting old, crusty, stale, and irrelevant again.

Related Posts (hand-picked just for you)

Using Regular Expressions to replace text in Xcode

Developing for iOS 7 (and supporting iOS 6)