iOS屬性反射:說白了,就是將兩個對象的所有屬性,用動態的方式取出來,並根據屬性名,自動綁值。(注意:對象的類,如果是派生類,就得靠其他方式來實現了,因為得到不該基類的屬性。)
本人常用的反射方式,有如下兩種:
- (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了