是否有可能使用ID访问对象的所有属性?
问题描述:
我有一个Object:aObject,它有属性a,b,c。是否有可能使用ID访问对象的所有属性?
我可以使用访问属性:
aObject.a
aObject.b
aObject.c
是否有可能访问使用ID的对象的所有属性?如
[aObject indexOf:0]
[aObject indexOf:1]
[aObject indexOf:2]
或类似的东西。
欢迎任何评论
答
KVC(键值编码)将允许您使用方法[anObject setValue:aValue forKey:@"a"]
设置属性值。
如果你真的想迭代每个属性,设置它的值,那么你需要下拉到Objective-C运行时。
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([anObject class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char * name = property_getName(property);
[anObject setValue:anyValue forKey:[NSString stringWithUTF8String:name]];
}
free(properties);
free(properties); – 0xced