Class Hierarchy
In Objective-C, each new class is derived from an already-existing class. The Car class described in Listings 3-1 and 3-2 is formed from NSObject, the root class of the Objective-C class tree. Each subclass adds or modifies state and behavior that it inherits from its parent, also called its “superclass.” The Car class adds several instance variables and methods to the vanilla NSObject it inherits.
Figure 3-2 shows some of the classes found in the iOS SDK and how they relate to each other in the class hierarchy. Strings and arrays descend from NSObject, as does the UIResponder class. UIResponder is the ancestor of all onscreen iOS elements. Views, labels, text fields, and sliders are children, grandchildren, or other descendants of UIResponder and NSObject.
Figure 3-2. All Cocoa Touch classes are descended from NSObject, the root of the class hierarchy tree.
Every class other than NSObject descends from other classes. UITextField is a kind of UIControl, which is in turn a kind of UIView, which is a UIResponder, which is an NSObject. Building into this object hierarchy is what Objective-C is all about. Child classes can do the following:
- Add new instance variables that are not allocated by their parent, also called the superclass. The Car class adds three: the make and model strings, and the year integer.
- Add new methods that are not defined by the parent. Car defines several new methods, letting you set the values of the instance variables and print out a report about the car.
- Override methods that the parents have already defined. The Car class’s init method overrides NSObject’s version. When sent an init message, a car object runs its version, not NSObject’s. At the same time, the code for init makes sure to call NSObject’s init method via [super init]. Referencing a parent’s implementation, while extending that implementation, is a core part of the Objective-C design philosophy.