[iOS KVC+Runtime , 获取类中的属性名,为不存在的key赋值]

有时候后端下发的json对象并不存在某个key(某个字段没有下发),
这时候使用kvc去获取对象的值,虽然不会报错(约定均返回字符串),但实际此model对象的某个属性值是为nil的

比如

UserInfo.h 有个属性 
@property (nonatomic, strong) NSString *userId;//用户ID

//当后端返回的json对象中不包含 userId 字段时,
//kvc解析不会报错, 但是 UserInfo的对象 userInofA,  userInofA.userId的值是为nil.
//若此时,将userInofA.userId塞入一个字典中,比如会导致程序崩溃.

以上, 就需要我们检测出这个未下发的字段(userId),

并且在kvc执行之后,将其nil的值修改为一个有意义的值,比如” “空字符串之类的.


下面,贴出一个runtime方法,轮询出本类的所有属性,

对为nil的属性重新赋值为有意义的字符串

#import "EPuserinfo.h"
#import <objc/runtime.h>


@interface EPuserinfo()
{
    NSString *status_proValue; //statues字段的值
}
@end

@implementation EPuserinfo




- (instancetype)initWithDict:(NSDictionary*)dict{

    if ([super init]) {

        //kvc
        [self setValuesForKeysWithDictionary:dict];

        //runtime检测是否有nil
        [self checkKeysWithValues];

    }
    return self;

}

- (void)checkKeysWithValues {

    unsigned int count ,i;

    //1.文档字段赋值
    //获取属性列表数组
    objc_property_t *propertyArray = class_copyPropertyList([self class], &count);

    for (i = 0; i < count; i++) {
        objc_property_t property = propertyArray[i];
        //获取属性名称字符串
        NSString *proKey = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        //获取属性对应的赋值
        id proValue = [self valueForKey:proKey];

        if (proValue) {

            //将非字符串数据转换为NSString
            if (![proValue isKindOfClass:[NSString class]]) {
                proValue = [NSString stringWithFormat:@"%@",proValue];
            }
            //重新赋值
            [self setValue:proValue forKey:proKey];

            //获取statues字段的value
            if ([proKey isEqualToString:@"status"]) {
                status_proValue = proValue;
            }
        } else {
            //值不存在,提示unKnown
            [self setValue:@"unKnown" forKey:proKey];
        }
    }
    free(propertyArray);


    //2.非文档字段(statusDec)-转码
    [self setDecValueForKey_StatusDec:@"statusDec"];
}


#pragma mark  statusDec字段(非文档)赋值转码
- (void)setDecValueForKey_StatusDec:(NSString*)proKey{

    if ([status_proValue isEqualToString:@"0"]) {
        [self setValue:@"审核通过" forKey:proKey];
    }
    if ([status_proValue isEqualToString:@"1"]) {
        [self setValue:@"待审核" forKey:proKey];
    }
    if ([status_proValue isEqualToString:@"2"]) {
        [self setValue:@"审核失败" forKey:proKey];
    }
    if ([status_proValue isEqualToString:@"9"]) {
        [self setValue:@"审核作废" forKey:proKey];
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值