Pages

Sunday, January 22, 2012

Type Introspection

NSObject is a root class, and so doesn’t have a superclass. It defines the basic framework for Objective-C objects and object interactions. It imparts to the classes and instances of classes that inherit from it the ability to behave as objects and cooperate with the runtime system.

A class that doesn’t need to inherit any special behavior from another class should nevertheless be made a subclass of the NSObject class. Instances of the class must at least have the ability to behave like Objective-C objects at run time. Inheriting this ability from the NSObject class is much simpler and much more reliable than reinventing it in a new class definition.

Type Introspection

Instances can reveal their types at runtime. The isMemberOfClass: method, defined in the NSObject class, checks whether the receiver is an instance of a particular class:

 if ( [anObject isMemberOfClass:someClass] )

    ...


The isKindOfClass: method, also defined in the NSObject class, checks more generally whether the receiver inherits from or is a member of a particular class (whether it has the class in its inheritance path):

if ( [anObject isKindOfClass:someClass] )
    ...
 
The set of classes for which isKindOfClass: returns YES is the same set to which the receiver can be statically typed.
Introspection isn’t limited to type information. Later sections of this chapter discuss methods that return the class object, report whether an object can respond to a message, and reveal other information.
NSObject class reference for more on isKindOfClass:, isMemberOfClass:, and related methods.

No comments:

Post a Comment