美文网首页
iOS解决字典和数组中输出乱码的问题

iOS解决字典和数组中输出乱码的问题

作者: 小小在流浪 | 来源:发表于2019-07-31 11:05 被阅读0次

    NSDictionaryNSArray添加一个分类,重写descriptionWithLocale方法,在该方法中拼接元素格式化输出。

    //重写系统的方法控制输出 indent 缩进
     - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
    

    代码@implementation NSDictionary (Log)

    #ifdef DEBUG
    //重写系统的方法控制输出 indent 缩进
    - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
    {
        NSMutableString *mStr = [NSMutableString string];
        NSMutableString *tabStr = [NSMutableString stringWithString:@""];
        for (int i = 0; i < level; i++) {
          [tabStr appendString:@"\t"];
        }
        [mStr appendString:@"{\n"];
    
        NSArray *allKey = self.allKeys;
        for (int i = 0; i < allKey.count; i++) {
            id value = self[allKey[i]];
            NSString *lastSymbol = (allKey.count == i + 1) ? @"":@",";
            if ([value respondsToSelector:@selector(descriptionWithLocale:indent:)]) {
                [mStr appendFormat:@"\t%@%@ = %@%@\n",tabStr,allKey[i],[value descriptionWithLocale:locale indent:level + 1],lastSymbol];
            } else {
                [mStr appendFormat:@"\t%@%@ = %@%@\n",tabStr,allKey[i],value,lastSymbol];
            }
        }
         [mStr appendFormat:@"%@}",tabStr];
       return mStr;
    }
    @end
    
    @implementation NSArray (Log)
    //重写系统的方法控制输出 indent 缩进
    -(NSString *)descriptionWithLocale:(id)locale indent:    (NSUInteger)level
    {
        NSMutableString *mStr = [NSMutableString string];
        NSMutableString *tabStr = [NSMutableString stringWithString:@""];
        for (int i = 0; i < level; i++) {
            [tabStr appendString:@"\t"];
        }
        [mStr appendString:@"[\n"];
        for (int i = 0; i < self.count; i++) {
            NSString *lastSymbol = (self.count == i + 1) ? @"":@",";
            id value = self[i];
            if ([value respondsToSelector:@selector(descriptionWithLocale:indent:)]) {
                [mStr appendFormat:@"\t%@%@%@\n",tabStr,[value descriptionWithLocale:locale indent:level + 1],lastSymbol];
            } else {
                [mStr appendFormat:@"\t%@%@%@\n",tabStr,value,lastSymbol];
            }
        }
        [mStr appendFormat:@"%@]",tabStr];
        return mStr;
    }
    #endif
    @end
    

    具体代码查看Github项目

    Github地址:iOSMultiTechnology

    相关文章

      网友评论

          本文标题:iOS解决字典和数组中输出乱码的问题

          本文链接:https://www.haomeiwen.com/subject/edrzrctx.html