1. 程式人生 > >iOS開發——輸出中文(字典和陣列)

iOS開發——輸出中文(字典和陣列)

      經常用網路請求返回Json資料,

    其中字典或者陣列列印輸出中文,非看不懂的Unicode編碼

1.支援NSLog輸出中文

2.支援控制檯po輸出中文

實現方式==》:

1.新建NSDictionary分類 (Xcode8 )



2.自動生成.h和.m檔案,在.m檔案如下實現(這樣就可以自動輸出中文了):

//
//  NSDictionary+Log.m
//
//  Created by 劉成利 on 2016/12/15.

#import "NSDictionary+Log.h"

@implementation NSDictionary (Log)

// NSLog輸出
- (NSString *)descriptionWithLocale:(id)locale
 {
         NSMutableString *string = [NSMutableString string];

        // 開頭有個{
         [string appendString:@"{\n"];
    
        // 遍歷所有的鍵值對
         [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                [string appendFormat:@"\t%@", key];
                 [string appendString:@" = "];
                 [string appendFormat:@"%@,\n", obj];
             }];
    
        // 結尾有個}
         [string appendString:@"}"];
    
         // 查詢最後一個逗號
         NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
         if (range.location != NSNotFound)
             [string deleteCharactersInRange:range];
    
         return string;
 }

// 輸出臺po命令輸出
-(NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
{
    NSMutableString *string = [NSMutableString string];
    
    // 開頭有個{
    [string appendString:@"{\n"];
    
    // 遍歷所有的鍵值對
    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [string appendFormat:@"\t%@", key];
        [string appendString:@" = "];
        [string appendFormat:@"%@,\n", obj];
    }];
    
    // 結尾有個}
    [string appendString:@"}"];
    
    // 查詢最後一個逗號
    NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
    if (range.location != NSNotFound)
        [string deleteCharactersInRange:range];
    
    return string;
}
@end


// 陣列輸出
@implementation NSArray (Log)
- (NSString *)descriptionWithLocale:(id)locale
 {
         NSMutableString *string = [NSMutableString string];
    
         // 開頭有個[
         [string appendString:@"[\n"];
    
         // 遍歷所有的元素
         [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                 [string appendFormat:@"\t%@,\n", obj];
             }];
    
         // 結尾有個]
         [string appendString:@"]"];
    
         // 查詢最後一個逗號
         NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
         if (range.location != NSNotFound)
             [string deleteCharactersInRange:range];
     
         return string;
}



@end