【发布时间】:2014-02-03 00:51:59
【问题描述】:
我一直有兴趣使用类似于以下代码行的东西来 自动构建我的对象(因为其中有很多具有相当多的属性):
MyObject *myObject = [[myObject alloc] init];
unsigned int numberOfProperties = 0;
objc_property_t *propertyArray = class_copyPropertyList([MyObject class], &numberOfProperties);
for (NSUInteger i = 0; i < numberOfProperties; i++)
{
objc_property_t property = propertyArray[i];
NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
if (propertyName)
{
id valueForProperty = [myObject valueForKey:propertyName];
[myObject setValue:valueForProperty forKey:propertyName];
}
}
free(propertyArray);
但是,我注意到,这段代码不仅会尝试在我的头文件中的属性上运行,还会尝试在我的所有实现属性上运行,这是我不想要的。
由于 Objective-C 实际上并没有区分公共属性和私有属性,我不知道该怎么做。关于如何表明我只对头文件中的属性感兴趣以有效地模拟相同的事情有什么想法吗?
【问题讨论】:
-
别这样,清晰胜于聪明。
-
该代码实际上并没有做任何事情。如果您想解释您实际尝试做的事情,我们或许可以建议一种现实的方式来做到这一点。
标签: objective-c introspection objective-c-runtime declared-property