Debug Logging in iOS Objective-C Apps – Pt. 2

Hey, it’s me again, sorry for not posting much… Anyway, I recently got fed up with my previous debug logging method and decided to remake it. Before I’d use it like this,

[VAPIHelper debugLog:@"AppDelegate" message:[NSString stringWithFormat:@"authTokenPresent is %@", self.authTokenPresent ? @"YES" : @"NO"]];

Now, with my new improved version it is simply this,

debugLog(@"authTokenPresent is %@", self.authTokenPresent ? @"YES" : @"NO");

As you can see, it is much simpler, handles NSStrings with format inline and shorter! Here’s how it works.
Firstly the macro that defines the debugLog signature is as follows:

#define debugLog(...) [VAPIHelper debugLog:[NSString stringWithFormat:@"%@:%@", @__FILE__, @__LINE__] message:[NSString stringWithFormat:__VA_ARGS__]]

As you can see it has the stringWithFormat builtin, so you don’t need to use that method to construct the string you want to output. Here’s the implementation of [VAPIHelper debugLog:],

+ (void)debugLog:(NSString *)location message:(NSString *)message {
    AppDelegate *delegate = getDelegate();
    if (delegate.debugOn) {
        NSString *debugMsg = [NSString stringWithFormat:@"%@: %@\n", location, message];
        NSLog(@"%@", debugMsg);
        dispatch_async(dispatch_get_main_queue(), ^{
            [delegate.debugTextView setText:[delegate.debugTextView.text stringByAppendingString:debugMsg]];
            NSRange range = NSMakeRange(delegate.debugTextView.text.length - 1, 1);
            [delegate.debugTextView scrollRangeToVisible:range];
        });
    }
}

Firstly I decided to make the getting of the delegate it’s own macro too, the () isn’t needed but makes it clear its a function call, it is simply:

(AppDelegate*)[[UIApplication sharedApplication]delegate]

I got tired of having this ugly snippet everywhere in my code, especially when I forget to typecast the id to an AppDelegate* type, it gives me so many warnings… So I decided to embrace macros to make my life easier and working with my codebases much more pleasant.

As for the rest of the code, it is just checking if debug is enabled on the current build, if so it will construct the string, print it, and display it on my custom UITextView that floats in front of the Parent View Controller, displaying all the debug logging so I don’t need to ssh for socat. Now that I think about it, I think ill stub out the debugLog function entirely if the build isn’t compiled with DEBUG set. It’d be better for security yeah. Anyway that’s all for now 😀

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.