对于那些做后端开发的工程师来说,看LOG解Bug应该是理所当然的事,但我接触到的移动应用开发的工程师里面,很多人并没有这个意识,查Bug时总是一遍一遍的试图重现,试图调试,特别是对一些不太容易重现的Bug经常焦头烂额,
iOS中 加强日志输出 开发技术总结
。而且iOS的异常机制比较复杂,Objective-C的语言驾驭也需要一定的功力,做出来的应用有时候挺容易产生崩溃闪退。一遍一遍的用XCode取应用崩溃记录、解析符号,通常不胜其烦,有时还对着解析出来的调用栈发呆,因为程序当时的内部状态常常难以看明白,只能去猜测。对于真机,日志没法保存,不好分析问题。所以有必要将日志保存到应用的Docunment目录下,并设置成共享文件,这样才能取出分析。
导入第三方:AFNetWorkinng
- (void)viewDidLoad{ [super viewDidLoad]; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager GET:@http://mobile.ximalaya.com/m/category_tag_list?category=entertainment&device=iPhone&type=album parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@%@, responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@%@, [error localizedDescription]); }]; }
给其写一个类目:Foundation+Log.m
#import<foundation foundation.h="">@implementation NSDictionary (Log)//+ (void)load//{// NSLog(@11);//}- (NSString *)descriptionWithLocale:(id)locale{ NSMutableString *str = [NSMutableString string]; [str appendString:@{]; [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [str appendFormat:@ %@ = %@, , key, obj]; }]; [str appendString:@}]; // 删除最后一个, NSRange range = [str rangeOfString:@, options:NSBackwardsSearch]; [str deleteCharactersInRange:range]; return str;}@end@implementation NSArray (Log)- (NSString *)descriptionWithLocale:(id)locale{ NSMutableString *str = [NSMutableString string]; [str appendString:@[]; [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [str appendFormat:@ %@,, obj]; }]; [str appendString:@]]; // 删除最后一个, NSRange range = [str rangeOfString:@, options:NSBackwardsSearch]; [str deleteCharactersInRange:range]; return str;}@end</foundation>最终效果:
小技巧:iOS - 将控制台Log日志转为输出为文本文件
1.在AppDelegate.m中创建函数实现以下代码块:- (void)redirectNSlogToDocumentFolder{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [paths objectAtIndex:0]; NSString *fileName = [NSString stringWithFormat:@MrNSLog.txt];// 注意不是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);}2.在didFinishLaunchingWithOptions中调用 : [self redirectNSlogToDocumentFolder];最后配置共享文件夹:
在应用程序的Info.plist文件中添加UIFileSharingEnabled键,并将键值设置为YES,