0%

iOS 编程:NSArray、NSDictionary 打印中文乱码问题

NSArray、NSDictionary 打印中文乱码问题

如果在 console 中遇到了 NSArrayNSDictionary 打印中文乱码问题,解决方法之一是创建 NSArray+ExtensionNSDictionary+Extension 两个 Category 分类。

⚠️ Xcode 8.0 之后使用 NSLog 打印时会产生该问题。

NSArray+Extension

-(NSString *)descriptionWithLocale:(id)locale
{
    NSMutableString *msr = [NSMutableString string];
    [msr appendString:@"["];
    for (id obj in self) {
        [msr appendFormat:@"\n\t%@,",obj];
    }
    //去掉最后一个逗号(,)
    if ([msr hasSuffix:@","]) {
        NSString *str = [msr substringToIndex:msr.length - 1];
        msr = [NSMutableString stringWithString:str];
    }
    [msr appendString:@"\n]"];
    return msr;
}

NSDictionary+Extension

-(NSString *)descriptionWithLocale:(id)locale
{
    NSMutableString *msr = [NSMutableString string];
    [msr appendString:@"{"];
    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [msr appendFormat:@"\n\t%@ = %@,",key,obj];
    }];
    //去掉最后一个逗号(,)
    if ([msr hasSuffix:@","]) {
        NSString *str = [msr substringToIndex:msr.length - 1];
        msr = [NSMutableString stringWithString:str];
    }
    [msr appendString:@"\n}"];
    return msr;
}

NSDictionary 的 value 为空造成的 crash

/**
 填充value为空造成的crash

 @return 修改后的NSDictionary
 */
//.h
- (NSDictionary *)deleteAllNULLValue;

//.m
- (NSDictionary *)deleteAllNULLValue {
    NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc] init];
    for (NSString *keyStr in self.allKeys) {
        if ([[self objectForKey:keyStr] isEqual:[NSNull null]]) {
            [mutableDic setObject:@"null" forKey:keyStr];
        }
        else{
            [mutableDic setObject:[self objectForKey:keyStr] forKey:keyStr];
        }
    }
    return mutableDic;
}

其他方法

  • GitHub:HYBUnicodeReadable

欢迎关注我的其它发布渠道