Thursday, October 24, 2013

Introduction to Introspection in Objective C

This article is intended for understanding of the beginners. You will not see any advance stuff here. I will be giving some basic introduction to Introspection and what are the syntaxes to perform the Introspection.

We may have an array of objects of different kind of classes. But we might need to be sure of the type of object before sending a message to the object. So How do we do this? We use introspection.


Using Introspection we can ask an Object what class are you? or What Methods do you implement?
So How do we perform Introspection? Here is how we do it..

All the Classes which inherit from NSObject know three methods.

isKindOfClass : This method returns whether an object is that kind of class. Object can be that class or Inheriting from that class. 

isMemberOfClass : isMemeberOfClass means are you that class, no Inheritance. Object should be specifically of that kind of class only. We might not need this normally. Generally we use isKindOfClass.

respondsToSelector : we use this method when we are not interested in what kind of class object is, but we just want to know whether object responds to the method or not. This method returns whether an object responds to the given method or not.

So that was quick introduction to the methods available for Introspection. Here are how we can use methods for Introspection.

usage of isKindOfClass 

if([obj isKindOfClass:[NSString class]]) {
// now we are safe to send methods of NSString to obj.
     NSString *s = [(NSString *)obj stringByAppendingString:@"abc"];

Here we are using class method of a class to get the class... :)

usage of respondsToSelctor

if ([obj respondsToSelector:@selector(<method name here>)]) {
   [obj <method name>]

Here we have used special @selector() directive. This directive converts the name of the method into a selector.

@selctor() returns something SEL. SEL is the Objective C "type" for the selectors.

SEL addSelector = @Selector(add);
SEL addToSelector = @Selector(addTo:withNumber:);

This was the brief introduction to Introspection and Selectors. We will come with a new article with more examples of using Selectors.

Happy Coding!!!!

No comments:

Post a Comment