writeToFile 写入失败问题 --->字典去空值

  1. 写入的必须是NSString,NSDate,NSArray,NSDictionary等基本数据类型

2.写入的数据不能为自定义类型或者Null (服务器返回的字典里,有个键对应的值为Null,搞了半天写不进去)

单层字典

- (void)saveUserInfoWithDictionary:(NSDictionary *)dict{
 
    // 去除空值
    NSMutableDictionary *dic = dict.mutableCopy;
    for (NSString * key in dic.allKeys) {
        id value = [dic valueForKey:key];
        if (value == nil || [value isKindOfClass:[NSNull class]]) {
            value = @"";
            [dic setValue:value forKey:key];
        }
    }
    
    // 保存本地
    if ([dic writeToFile:kUserInfoPath atomically:YES]) {
        NSLog(@"保存用户信息成功");
    }
}

多层字典

如果字典是多层的, 既字典里面包含字典,或者字典里包含数组,数组里又是字典,可以写个递归


@implementation NSDictionary (Extension)

// 会遍历每一个键值对, 建议让后台的小伙伴尽量别返回null
- (NSDictionary *)removeNull{
    
    // 去除空值
    NSMutableDictionary *dic = self.mutableCopy;
    for (NSString * key in dic.allKeys) {
        id value = [dic valueForKey:key];
        
        // 字典里包含字典
        if ([value isKindOfClass:[NSDictionary class]]) {
            value = [value removeNull];
            [dic setValue:value forKey:key];
        }
        
        // 如果是数组
        else if ([value isKindOfClass:[NSArray class]]) {
            NSMutableArray *array = [value mutableCopy];
            for (int i= 0; i

作者:请不要叫我呆头鹅
来源:CSDN
原文:https://blog.csdn.net/lg767201403/article/details/71485641

你可能感兴趣的:(writeToFile 写入失败问题 --->字典去空值)