Skip to content

Instantly share code, notes, and snippets.

@sora0077
Created May 5, 2013 07:48
Show Gist options
  • Save sora0077/5520057 to your computer and use it in GitHub Desktop.
Save sora0077/5520057 to your computer and use it in GitHub Desktop.
ログ出力をもっと便利に簡単にするマクロ ref: http://qiita.com/sora0077@github/items/ea0cf4a1a2ec3f0333d7
id var1 = @"hoge";
VARLOG(var1);
id var2 = @{@"huga": @"hoge"};
VARLOG(var1, var2);
// output
// -[AppDelegate application:didFinishLaunchingWithOptions:] at LINE:78
// {
// var1 = hoge;
// }
//
// -[FKAppDelegate application:didFinishLaunchingWithOptions:] at LINE:81
// {
// var1 = hoge;
// var2 = {
// huga = hoge;
// };
// }
VARLOG(@[@"hoge", @"huga"]); -> NG
VARLOG([NSString stringWithFormat:@"%@", @"hoge"]); -> NG
#define VAR(...) _VAR(@""#__VA_ARGS__, __VA_ARGS__)
//#define VAR(var, ...) NSDictionaryOfVariableBindings(var, ##__VA_ARGS__)
#define _VAR(...) \
^NSString *(NSString *format, ...) {\
va_list args;\
format = [format stringByReplacingOccurrencesOfString:@", " withString:@","];\
format = [format stringByReplacingOccurrencesOfString:@" ," withString:@","];\
NSArray *keys = [format componentsSeparatedByString:@","];\
\
NSMutableArray *objects = [NSMutableArray arrayWithCapacity:keys.count];\
\
va_start(args, format);\
for (int i = 0; i < keys.count; i++) {\
id object = va_arg(args, id);\
object = object ? object : @"nil";\
[objects addObject:object];\
}\
va_end(args);\
\
NSMutableString *buffer = [NSMutableString stringWithString:@"{\n"];\
\
[objects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\
id key = [keys objectAtIndex:idx];\
id description = obj;\
if ([obj respondsToSelector:@selector(descriptionWithLocale:indent:)]) {\
description = [obj descriptionWithLocale:nil indent:1];\
}\
[buffer appendFormat:@"\t%@ = %@;\n", key, description];\
}];\
\
[buffer appendString:@"}"];\
return buffer;\
}(__VA_ARGS__)
#define VARLOG(var, ...) NSLog(@"\n%s at LINE:%d\n%@\n\n", __func__, __LINE__, VAR(var, ##__VA_ARGS__))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment