NSLog stuff

July 22, 2015

post image

Hi again,

It’s been a looong day to write down something to share to the world something that I think it might be heplful. Today I will be talking about NSLog stuff in iOS development. Interest, huh?

NSLog is a useful stuff to print log in objective-C, I have been using it a lot and really effective in my opinions. But is there any thing cool of it? Hmm, nice question, today I will show you 2 things about this, here are: How to custom a NSLog and More cool things.

So, again, just do it.

How to custom a NSLog

This is kind of fun, too many ways you can do that. For example, you could define it as a macro, maybe in your .pch file:

#ifdef DEBUG
#define NLLog(x, ...) NSLog(@"%s %d: " x, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define NLLog(x, ...)

Yeah, now we can test this:

int i = 10;
NLLog(@"%d", i);

And it will show like:

2015-07-22 15:53:42.913 testConsole[1076:109400] main 39: 10 Pretty cool, right?

Just make sure your project is enable DEBUG mode, by folowing the pic below, it simply make sure in processor macros, DEBUG=1.

Enable debug mode

And another way:

#ifdef DEBUG
#define NLLogDebug(format, ...) \
NSLog(@"<%s:%d> %s, " format, \
strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
#define NLLogDebug(format, ...)
int i = 10;
NLLogDebug(@"check this %d", i);

It will show 2015-07-22 15:55:14.076 testConsole[1076:109400] <main.m:43> int main(int, const char **), check this 10.

Above we have been using macros, so now turn to use C code, here is a sample:

void NLLogUsingC(NSString *format, ...){
    va_list args;
    va_start(args, format);
    NSLogv(format, args);

And use it like:

int i = 10;
NLLogUsingC(@"%d", i);

Result: 2015-07-22 15:59:18.349 testConsole[1087:113110] 10.

More cool things

We have used __LINE__, or __FUNCTION__ …, so what are they? How they work? or Where are they from? I’m gonna answer you right now.

| Macro                | Format   | Description
  __func__               %s         Current function signature
  __LINE__               %d         Current line number
  __FILE__               %s         Full path to source file
  __PRETTY_FUNCTION__    %s         Like __func__, but includes verbose
                                    type information in C++ code. 

Where do we get them? Well, The C preprocessor provides a few macros.

So that much about NSLog, right? Hope you have fun while reading this. Let’s try it yourself and enjoy. :D