
This video is only available to subscribers. Start a subscription today to get access to this and 472 other videos.
Class Introspection
Episode
#38
|
18 minutes
| published on
October 18, 2012
Subscribers Only
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 Reference
- Understanding C Pointers & Arrays - This might be helpful if the C array usage was confusing.
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);