当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS反射机制

iOS反射机制

2019年05月12日  | 移动技术网移动技术  | 我要评论

ios属性反射:说白了,就是将两个对象的所有属性,用动态的方式取出来,并根据属性名,自动绑值。(注意:对象的类,如果是派生类,就得靠其他方式来实现了,因为得到不该基类的属性。)

本人常用的反射方式,有如下两种:


从一个自定义实体类->自定义实体类
从一个nsdictionary->自定义实体类(此方式最最常用,如网络json数据会组成nsdictionary。sqlite查询数据,可以用第三方组成nsdictionary)
直接上码,(这里码在nsobject类别中)
获取对象所有属性:
- (nsarray*)propertykeys

{

    unsigned int outcount, i;

    objc_property_t *properties = class_copypropertylist([self class], &outcount);

    nsmutablearray *keys = [[nsmutablearray alloc] initwithcapacity:outcount];

    for (i = 0; i < outcount; i++) {

        objc_property_t property = properties[i];

        nsstring *propertyname = [[nsstring alloc] initwithcstring:property_getname(property) encoding:nsutf8stringencoding];

        [keys addobject:propertyname];

    }

    free(properties);

    return keys;

}

 

 

- (bool)reflectdatafromotherobject:(nsobject*)datasource

{

    bool ret = no;

    for (nsstring *key in [self propertykeys]) {

        if ([datasource iskindofclass:[nsdictionary class]]) {

            ret = ([datasource valueforkey:key]==nil)?no:yes;

        }

        else

        {

            ret = [datasource respondstoselector:nsselectorfromstring(key)];

        }

        if (ret) {

            id propertyvalue = [datasource valueforkey:key];

            //该值不为nsnull,并且也不为nil

            if (![propertyvalue iskindofclass:[nsnull class]] && propertyvalue!=nil) {

                [self setvalue:propertyvalue forkey:key];

            }           

        }

    }

    return ret;

}

 

/////使用方法
nsdictionary *dicjsondata;


entityobject *objvalue;


[objvalue reflectdatafromotherobject:dicjsondata];//这样就可以完成对象的自动赋值了,

 


//你还在使用

objvalue.value = [dicjsondata objectforkey:@"value"];//out了

 


 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网