1. 程式人生 > >NSLog列印中文

NSLog列印中文

以前使用NSLog列印中文就是重寫下面的方法.

- (NSString *)descriptionWithLocale:(nullable id)locale;

然而在某個版本(我也記不清楚是什麼版本了).這個方法失效了.NSLog不會走這個方法.當時簡單的查閱了一下資料就改了…今天看了看一個特別老舊的專案沒有輸出中文.想到之前改的這個事情了.純屬記錄一下吧.
在新版本中使用

- (NSString *)descriptionWithLocale:(nullable id)locale indent:(NSUInteger)level;

來代替之前的方法.

:下面貼出具體程式碼

@implementation NSArray (Log)

/// old
- (NSString *)descriptionWithLocale:(id)locale {
    NSMutableString *strM = [NSMutableString string];
    [strM appendString:@"(\n"];
    [self enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //  判斷是否是最後一個元素
        if (idx == self.count - 1) {
            [strM appendFormat:@"\t%@\n", obj];
        } else {
            [strM appendFormat:@"\t%@,\n", obj];
        }
    }];
    [strM appendString:@")\n"];
    return strM;
}

/// new
- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level {
    NSMutableString *strM = [NSMutableString string];
    [strM appendString:@"(\n"];
    [self enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //  判斷是否是最後一個元素
        if (idx == self.count - 1) {
            [strM appendFormat:@"\t%@\n", obj];
        } else {
            [strM appendFormat:@"\t%@,\n", obj];
        }
    }];
    [strM appendString:@")\n"];
    return strM;
}


@end


@implementation NSDictionary (Log)

/// old
- (NSString *)descriptionWithLocale:(id)locale {
    NSMutableString *strM = [NSMutableString string];
    [strM appendString:@"{\n"];
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [strM appendFormat:@"\t%@ = %@;\n", key, obj];
    }];
    [strM appendString:@"}\n"];
    return strM;
}

/// new
- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level {
    NSMutableString *strM = [NSMutableString string];
    [strM appendString:@"{\n"];
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [strM appendFormat:@"\t%@ = %@;\n", key, obj];
    }];
    [strM appendString:@"}\n"];
    return strM;
}

@end