iOS 调试 之 打印
参考:http://m.blog.csdn.net/blog/HookyStudent/42964317
参考:http://m.blog.csdn.net/blog/laencho/25190639
1. 打印信息
1.1. 信息宏
NSLog(@"%s:%d obj=%@", __func__, __LINE__, obj);
类名: NSString *class = [NSString stringWithUTF8String:object_getClassName(self)];
函数名:__func__
所在行号:__LINE__
当前文件路径:__FILE__
打印当前函数或方法:__PRETTY_FUNCTION__
以上打印内容都是C字符串,所以需要转化,例如:
[NSString stringWithFormat:@"%s", __func__]
1.2. 打印宏
#ifdef DEBUG # define DebugLog(fmt, ...) NSLog((@"\n[文件名:%s]\n""[函数名:%s]\n""[行号:%d] \n" fmt), __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DebugLog(...); #endif
2. 打印运行时信息
NSStringFromSelector(SEL) 获取selector的名字
NSStringFromSelector(_cmd) 获取当前方法名
NSStringFromClass([object class]) 获取object的类名
NSThread callStackSymbols] 获取当前线程的栈,是一个NSArray,包含堆栈中所有函数名。
3. 打印到文件
- (void)redirectNSlogToDocumentFolder { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [paths objectAtIndex:0]; NSString *fileName = [NSString stringWithFormat:@"dr.log"];// 注意不是NSData! NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName]; // 先删除已经存在的文件 NSFileManager *defaultManager = [NSFileManager defaultManager]; [defaultManager removeItemAtPath:logFilePath error:nil]; // 将log输入到文件 freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout); freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr); }