對于那些做后端開發(fā)的工程師來說,看LOG解Bug應(yīng)該是理所當(dāng)然的事,但我接觸到的移動(dòng)應(yīng)用開發(fā)的工程師里面,很多人并沒有這個(gè)意識(shí),查Bug時(shí)總是一遍一遍的試圖重現(xiàn),試圖調(diào)試,特別是對一些不太容易重現(xiàn)的Bug經(jīng)常焦頭爛額,
iOS中 加強(qiáng)日志輸出 開發(fā)技術(shù)總結(jié)
。而且iOS的異常機(jī)制比較復(fù)雜,Objective-C的語言駕馭也需要一定的功力,做出來的應(yīng)用有時(shí)候挺容易產(chǎn)生崩潰閃退。一遍一遍的用XCode取應(yīng)用崩潰記錄、解析符號(hào),通常不勝其煩,有時(shí)還對著解析出來的調(diào)用棧發(fā)呆,因?yàn)槌绦虍?dāng)時(shí)的內(nèi)部狀態(tài)常常難以看明白,只能去猜測。對于真機(jī),日志沒法保存,不好分析問題。所以有必要將日志保存到應(yīng)用的Docunment目錄下,并設(shè)置成共享文件,這樣才能取出分析。
導(dǎo)入第三方: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]); }]; }
給其寫一個(gè)類目: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:@}]; // 刪除最后一個(gè), 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:@]]; // 刪除最后一個(gè), NSRange range = [str rangeOfString:@, options:NSBackwardsSearch]; [str deleteCharactersInRange:range]; return str;}@end</foundation>最終效果:
小技巧:iOS - 將控制臺(tái)Log日志轉(zhuǎn)為輸出為文本文件
1.在AppDelegate.m中創(chuàng)建函數(shù)實(shí)現(xiàn)以下代碼塊:- (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]; // 先刪除已經(jīng)存在的文件 NSFileManager *defaultManager = [NSFileManager defaultManager]; [defaultManager removeItemAtPath:logFilePath error:nil]; // 將log輸入到文件 freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], a+, stdout); freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], a+, stderr);}2.在didFinishLaunchingWithOptions中調(diào)用 : [self redirectNSlogToDocumentFolder];最后配置共享文件夾:
在應(yīng)用程序的Info.plist文件中添加UIFileSharingEnabled鍵,并將鍵值設(shè)置為YES,