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
Also available in: Atom
Keywords
- blog (1)
- iphone (4)
- mac (4)
- programming (5)
- ruby (6)
- ruby on rails (2)
- snippet (1)
- statistics (1)