连接objc_property_t

时间:2016-04-26 14:58:54

标签: objective-c properties concatenation exc-bad-access

我有一个名为dto的对象。这个对象是另一个的孩子,他父亲的最高级是NSObject。我想获得dto及其所有超类的所有属性。实际上,当我想在我的bucle中看到propertyName时,我得到了EXC_BAD_ACCESS。非常感谢你!

unsigned int i, superPropertyCount, propertyCount;
objc_property_t *properties = class_copyPropertyList([dto class], &propertyCount);

if ([[dto class] isSubclassOfClass:[NSObject class]])
{
    memcpy(properties, properties, propertyCount * sizeof(objc_property_t));
    id superClass = [[dto class] superclass];
    while ([superClass isSubclassOfClass:[NSObject class]])
    {
        objc_property_t *superProperties = class_copyPropertyList(superClass, &superPropertyCount);

        properties = malloc((propertyCount + superPropertyCount) * sizeof(objc_property_t));

        if (properties != NULL)
        {
            memcpy(properties, properties, propertyCount * sizeof(objc_property_t));
            memcpy(properties+propertyCount, superProperties, superPropertyCount * sizeof(objc_property_t));
        }
        propertyCount = propertyCount + superPropertyCount;
        superClass = [superClass superclass];
    }
}

for (i = 0; i < propertyCount; i++)
{
    objc_property_t property = properties[i];
    NSString *propertyName = [NSString stringWithUTF8String: property_getName(property)];
}

1 个答案:

答案 0 :(得分:4)

你在

的属性处丢失指针
properties = malloc((propertyCount + superPropertyCount) * sizeof(objc_property_t));

下一行代码:

memcpy(properties, properties, propertyCount * sizeof(objc_property_t));

没有任何效果。

顺便说一句。不要忘记使用class_copyPropertyListmalloc释放已分配的内存。