C# to Objective-C - Part 6 : Reflection

Stephen Zaharuk / Tuesday, November 27, 2012

In today’s post I’m going to show you some basic reflection in Objective-C. To start off, lets take a look at probably the most common use case for reflection:

Finding the type of an object

C#:
Type t = typeof(MyClass);

Objective-C:
Class c = [MyClass class];

As you can see, in Objective-C we use the keyword “Class” instead of Type. Also we’re accessing a static method off of the class as opposed to calling a method and passing in the class.  

Get the type of an instantiated object:

C#:
Type t = myObj.GetType();

Objective-C:
Class c = myObj.class;

Again, there isn’t much different here. Basically we  just access a property called “class” as opposed to calling a method.

Now lets look at how you would check to see if a class derives from a certain type.

C#:
bool x = self is Window;

Objective-C:
BOOL x = [self isKindOfClass:[UIView class]];

And to see if a class implements a interface/protocol:

C#:
bool x = this is IEnumerable;

Objective-C:
BOOL x = [self conformsToProtocol:@protocol(IGGridViewDataSource)];

Lets move on to a more advanced topics.

Find all properties on a object

C#:
using System. Reflection;

PropertyInfo[] props = myObj.GetType().GetProperties();
foreach(PropertyInfo pi in props)
{
   string actualName = pi.name;
}

Objective-C:
#import <objc/runtime.h>

objc_property_t *properties = class_copyPropertyList([myObj class], &outCount);
for(i = 0; i < outCount; i++)
{
   objc_property_t property = properties[i];
   const char* name = property_getName(property);
   NSString* actualName = [NSString stringWithUTF8String:name];
}


Access a property on an object, with just a name

C#:
object val = myObj.GetType().GetProperty(“PropertyName”).GetValue(myObj, null);

Objective-C:
id val = [myObj valueForKey:@"propName"];


Invoke a method off an object, with just a name

C#:
object val = myObj.GetType().GetMethod(“MethodWithParam”).Invoke(myObj, new object[]{“param”});

Objective-C:
SEL method = NSSelectorFromString(@”methodWithParam:”);
id val = [myObj performSelector:method withObject:@"param"];

And thats a look at some basic reflection. 

If you found this helpful, check out the rest of this series so far. 

By Stephen Zaharuk (SteveZ)