Retired Document
Important: This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
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:
You can call introspection methods as runtime checks to help you avoid problems such as exceptions, which, for example, would occur if you send a message to an object that cannot respond to it.
You can also use introspection to help locate an object in the inheritance hierarchy, which would give you information about the object’s capabilities.
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 theclass
andsuperclass
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 aSEL
-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.
Copyright © 2018 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2018-04-06