iOS attribute reflection: To put it bluntly, all the properties of two objects are taken out dynamically and automatically bound according to the attribute name. (Note: The class of an object, if it is a derived class, has to be implemented in other ways because the properties of the base class should not be obtained.) )
The usual way of reflection, like the following two kinds:
Customizing entity classes from a custom entity class
Custom entity classes from one nsdictionary-> (this is most commonly used, such as the network JSON data that makes up nsdictionary. SQLite query data, can be composed of third-party components Nsdictionary)
Directly on the code, (here the code in the NSObject category)
Get all properties of an object:
-(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 inch [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];
The value is not nsnull and is not nil
if (![ PropertyValue Iskindofclass:[nsnull class]] && Propertyvalue!=nil) {
[Self setvalue:propertyvalue forkey:key];
}
}
}
return ret;
}
How to use
Nsdictionary *dicjsondata;
Entityobject *objvalue;
[ObjValue Reflectdatafromotherobject:dicjsondata]; This completes the automatic assignment of the object,
Are you still using the following method?
Objvalue.value = [Dicjsondata objectforkey:@ "value"];
It's out!
iOS reflex mechanism: use of objc_property_t