美文网首页
解决Xcode中文乱码及GBK转码问题

解决Xcode中文乱码及GBK转码问题

作者: 863cda997e42 | 来源:发表于2020-05-28 10:59 被阅读0次

    数组乱码

    #import "NSArray+Log.h"
    @implementation NSArray (Log)
    
    /**
     解决数组输出中文乱码的问题
     @return 输出结果
     */
    
    - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level{
        
        NSMutableString *string = [NSMutableString stringWithString:@"[\n"];
        
        [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            for (int i = 0; i <= level; i++) {
                [string appendFormat:@"\t"];
            }
            if ([obj isKindOfClass:[NSDictionary class]] || [obj isKindOfClass:[NSArray class]]) {
                [string appendFormat:@"%@,\n", [obj descriptionWithLocale:locale indent:level +1]];
            } else {
                [string appendFormat:@"%@,\n", obj];
            }
        }];
        //删除末尾的逗号
        if ([string hasSuffix:@",\n"]) {
            [string deleteCharactersInRange:NSMakeRange(string.length - 2, 1)]; // 删除最后一个逗号
        }
        
        for (int i = 0; i < level; i++) {
            [string appendFormat:@"\t"];
        }
        [string appendString:@"]"];
        
        return string;
    }
    
    @end
    

    字典乱码

    #import "NSDictionary+Log.h"
    
    @implementation NSDictionary (Log)
    
    /**
    解决字典输出中文乱码的问题
    @return 输出结果
    */
    
    - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level{
    
        NSMutableString *string = [NSMutableString stringWithCapacity:42];
        [string appendFormat:@"{\n"];
    
        [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    
            for (int i = 0; i <= level; i++) {
                [string appendFormat:@"\t"];
            }
            
            if ([obj isKindOfClass:[NSDictionary class]] || [obj isKindOfClass:[NSArray class]]) {
                [string appendFormat:@"%@ = %@,\n", key, [obj descriptionWithLocale:locale indent:level +1]];
            } else {
                [string appendFormat:@"%@ = %@,\n", key, obj];
            }
        }];
        
        //删除最后的一个逗号
        if ([string hasSuffix:@",\n"]) {
            [string deleteCharactersInRange:NSMakeRange(string.length - 2, 1)]; // 删除最后一个逗号
        }
           
        for (int i = 0; i < level; i++) {
            [string appendFormat:@"\t"];
        }
        [string appendString:@"}"];
    
        return string;
    }
    

    GBK转码

    + (NSData *)dataWithGBKData:(NSData *)data {
        NSStringEncoding gbk = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        NSString *string = [[NSString alloc] initWithData:data encoding:gbk];
        return  [string dataUsingEncoding:NSUTF8StringEncoding];
    }
    

    相关文章

      网友评论

          本文标题:解决Xcode中文乱码及GBK转码问题

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