mercredi 13 mai 2015

Swift nested property reflection in objC

In Swift I have a class that has a nested class and the nested class is also a property on my class. So for example:

public class DemoObject: NSObject {

    dynamic var nestObject: DemoObject.NestedObject = DemoObject.NestedObject()

    public class NestedObject: NSObject {

    }

}

Now I have a piece of objC code that I want to use and fetch the properties of this class.

I would do that with something like:

unsigned int count;
objc_property_t *props = class_copyPropertyList(objectClass, &count);
for (unsigned int i = 0; i < count; i++) {
    objc_property_t property = props[i];

    NSString *propertyName = @(property_getName(property));
    NSString* propertyType = @(property_getAttributes(property));
}

In this piece of code, the variable objectClass contains the class of my DemoObject.

Once I loop through the props array I notice that the property type of my property is NestedObject instead of DemoObject.NestedObject. So when I get the name of the class associated with the property and try to use NSClassFromString() it returns a nil object. (Of course, that class does not exist).

But it gets worse. If I try to manually instantiate my NestedObject using NSClassFromString(@"DemoObject.NestedObject") it also returns nil.

It does work if I use the "mangled" name for the class, like this:

Class tCl = NSClassFromString(@"_TtCC15RealmNestedDemo10DemoObject12NestedObject");

Except I don't have that information available in my objC code. I think, at least not from the objc_property_t object, right?





Aucun commentaire:

Enregistrer un commentaire