连接 objc_property_t

Concatenate objc_property_t

我有一个 object 名为 dto。这个object是另一个的child,他的父亲最高class是NSObject。我想获得 dto 及其所有 superclasses 的所有属性。实际上,当我想在我的 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)];
}

您正在丢失位于

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

下一行代码:

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

没有任何影响。

顺便说一句。不要忘记使用 class_copyPropertyListmalloc.

释放分配的内存