iPhone Code Snippets: NSLog Extended

Situation

A number of NSLog statements within the source code of an iPhone project, e.g.

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    NSLog(@"App did finish launching.");

    // ...

Problem

The filename and the line number shall be displayed in addition to the log string when compiling for the Debug configuration. The output shall be completely disabled for the Release configuration.

Solution

Inspired by John Muchows post Filename and Line Number with NSLog: Part II and modified as follows:

LogHelper.h:
#if DEBUG
#define CMLog(format, ...) [LogHelper logWithPath:__FILE__ line:__LINE__ string:(format), ## __VA_ARGS__]
#else
#define CMLog(format, ...)
#endif

@interface LogHelper : NSObject {
}

+ (void)logWithPath:(char *)path line:(NSUInteger)line string:(NSString *)format, ...;
LogHelper.m:
#import "LogHelper.h" 

@implementation LogHelper

+ (void)logWithPath:(char *)path line:(NSUInteger)line string:(NSString *)format, ... {
    NSString *pathString = [[NSString alloc] initWithBytes:path
                                                    length:strlen(path)
                                                  encoding:NSUTF8StringEncoding];

    va_list argList;
    va_start(argList, format);
    NSString *formattedString = [[NSString alloc] initWithFormat:format 
                                                       arguments:argList];
    va_end(argList);

    NSLog([NSString stringWithFormat:@"%@ (%d): %@", 
           [pathString lastPathComponent], 
           line, 
           formattedString]);
    [formattedString release];
}

@end

After creating the file, control-click Target > AppName, select Get Info, tab Build, configuration Debug and add "-DDEBUG" to the setting Other C Flags. Finally replace all NSLog statements by the new CMLog makro.

Keywords: iphone, programming, snippet

Added by Thomas Dohmke 539 days ago (1 Comment)

Also available in: Atom

Twitter

Follow us on Twitter:

Keywords