對于那些做后端開發的工程師來說,看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,