Introspection

Introspection refers to the inherent ability of an object to divulge, upon request, its essential characteristics at runtime. By sending objects certain messages, you can ask them questions about themselves as objects and the Objective-C runtime provides you with answers. Introspection is an important coding tool because it makes your programs more efficient and robust. Here are a couple of examples of how introspection might be useful:

Introspection

Types of Introspection Information

The NSObject protocol, which is adopted by the NSObject class, defines introspection methods that yield the following kinds of information about an object:

  • Class membership. To determine if an object inherits, directly or indirectly, from a particular class, send it an isKindOfClass: message and evaluate the result. This method tells you if the object is a direct instance of the given class. You can also use the class and superclass methods to obtain the class or superclass of an object and then use that result in comparison operations.

  • Messages responded to. To find out if an object’s class or superclass implements a method, send the object a respondsToSelector: message. The parameter is a SEL-typed value constructed from the signature of the method using the @selector directive. For example:

    BOOL doesRespond = [anObject respondsToSelector:@selector(writeToFile:atomically:)];
  • Protocol conformance. If a class conforms to a formal protocol, you can expect it to implement the required methods of that protocol and send messages to it accordingly. Use the conformsToProtocol: method to obtain this information. You specify the argument of this method using the @protocol directive.

Prerequisite Articles

Definitive Discussion