Episode #38

Class Introspection

18 minutes
Published on October 18, 2012

This video is only available to subscribers. Get access to this video and 584 others.

In this episode I create an application to introspect classes to list out methods and instance variables using Objective-C's runtime features. Bonus: Can you spot the memory leak?

Episode Links

Objective-C Runtime operations

There are a number of introspection capabilities that Objective-C provides. In this episode, I covered method and ivar retrieval.

Fetching methods in a Class

Class class = [NSString class];
unsigned int count;
Method *methods = class_copyMethodList(class, &count);

// iterate over them and print out the method name
for (int i=0; i<count; i++) {
  Method *method = methods[i];
  SEL selector = method_getName(method);
  NSLog(@"Method: %@", NSStringFromSelector(selector));
}

Listing a Class's instance variables


Class class = [UITableView class];
unsigned int count;
Ivar *ivars = class_copyIvarList(class, &count);

// iterate over them and print out the method name
for (int i=0; i<count; i++) {
  Ivar *ivar = ivars[i];
  NSString *name = ivar_getName(ivar);
  NSLog(@"ivar: %@", name);
}

Freeing memory

Note: I actually forgot to release the memory for these in the episode (whoops!)

Make sure that you free the memory for these arrays (it's easy to forget, especially after using ARC for a while). Since these methods begin with the word "copy", this signifies that we now own the reference to this memory.

You can free the memory by calling the C method free:

free(methods);
free(ivars);