Saturday, November 23, 2013

Customizing NSLog


Customizing NSLog:
================
Search for “preprocessing” and locate the section titled “Preprocessor Macros”. Next, simply add “DEBUG=1″ to the Debug section.


ExtendNSLogFunctionality.h
-----------------------------------
#import
#ifdef DEBUG
#define NSLog(args...) ExtendNSLog(__FILE__,__LINE__,__PRETTY_FUNCTION__,args);
#else
#define NSLog(x...)
#endif
void ExtendNSLog(const char *file, int lineNumber, const char *functionName, NSString *format, ...);



ExtendNSLogFunctionality.m
-----------------------------------
#import "ExtendNSLogFunctionality.h"
void ExtendNSLog(const char *file, int lineNumber, const char *functionName, NSString *format, ...)
{
    // Type to hold information about variable arguments.
    va_list ap;
    // Initialize a variable argument list.
    va_start (ap, format);
    // NSLog only adds a newline to the end of the NSLog format if
    // one is not already there.
    // Here we are utilizing this feature of NSLog()
    if (![format hasSuffix: @"\n"])
    {
        format = [format stringByAppendingString: @"\n"];
    }
    NSString *body = [[NSString alloc] initWithFormat:format arguments:ap];
    // End using variable argument list.
    va_end (ap);
    NSString *fileName = [[NSString stringWithUTF8String:file] lastPathComponent];
    fprintf(stderr, "(%s) (%s:%d) %s",
            functionName, [fileName UTF8String],
            lineNumber, [body UTF8String]);
}



Prefix.pch
-----------
#ifdef __OBJC__
    #import
    #import
    #import "ExtendNSLogFunctionality.h"
#endif


Example:
========
int result = 20;
NSLog(@"Value of result : %d", result);

(­[AppDelegate application:didFinishLaunchingWithOptions:]) (AppDelegate.m:21) Value of result : 20







No comments: