Wednesday 7 July 2010

Reflection

Like all emotional languages, Objective C has the ability to reflect upon itself.

This means given a class you can tell stuff about the class such as its name, what properties it has and so on.

I want to do this as I have some classes in my app and I want the user to be able to customise the options for them. Now I could of course create an XML file that contains the options that the user could change which I could then read into an NSDictionary or something and get my classes to work on them. But this is repetition.

I would much rather the options class could just read the properties of my class and display these to the user.

Reflection is slightly complicated as it needs some fairly low level C code. This is the Objective way!

 In Objective C each object is actually a struct that contains a pointer to an object called Class. This Class object contains all the information about the properties and methods that that object has.

We can access this class by calling

[ourObject class]; 


To access the reflection functions you need to

#import <objc\runtime.h>


Then the following code will get the properties and loop through them, grabbing the name from each property:


        unsigned int outCount;
        objc_property_t *classProperties = class_copyPropertyList([self class], &amp;outCount);       
        for (int i = 0; i &lt; outCount; i++)
        {
            objc_property_t property = classProperties[i];
            const char *propName = property_getName(property);

            

            // Do something with the name here ...!


        }

No comments:

Post a Comment