天天看點

ios developer tiny share-20160802

今天講NSObject類,所有類的基類。再講下UIButton、UIControl、UIView、UIResponder、NSObject這幾個類的繼承關系。

The Root Class Provides Base Functionality

In the same way that all living organisms share some basic “life” characteristics, some functionality is common across all objects in Objective-C.

When an Objective-C object needs to work with an instance of another class, it is expected that the other class offers certain basic characteristics and behavior. For this reason, Objective-C defines a root class from which the vast majority of other classes inherit, called NSObject. When one object encounters another object, it expects to be able to interact using at least the basic behavior defined by the NSObject class description.

When you’re defining your own classes, you should at a minimum inherit from NSObject. In general, you should find a Cocoa or Cocoa Touch object that offers the closest functionality to what you need and inherit from that.

If you want to define a custom button for use in an iOS app, for example, and the provided UIButton class doesn’t offer enough customizable attributes to satisfy your needs, it makes more sense to create a new class inheriting from UIButton than from NSObject. If you simply inherited from NSObject, you’d need to duplicate all the complex visual interactions and communication defined by the UIButton class just to make your button behave in the way expected by the user. Furthermore, by inheriting from UIButton, your subclass automatically gains any future enhancements or bug fixes that might be applied to the internal UIButton behavior.

The UIButton class itself is defined to inherit from UIControl, which describes basic behavior common to all user interface controls on iOS. The UIControl class in turn inherits from UIView, giving it functionality common to objects that are displayed on screen. UIView inherits from UIResponder, allowing it to respond to user input such as taps, gestures or shakes. Finally, at the root of the tree, UIResponder inherits from NSObject, as shown in Figure 1-3.

Figure 1-3  UIButton class inheritance

ios developer tiny share-20160802

This chain of inheritance means that any custom subclass of UIButton would inherit not only the functionality declared by UIButton itself, but also the functionality inherited from each superclass in turn. You’d end up with a class for an object that behaved like a button, could display itself on screen, respond to user input, and communicate with any other basic Cocoa Touch object.

It’s important to keep the inheritance chain in mind for any class you need to use, in order to work out exactly what it can do. The class reference documentation provided for Cocoa and Cocoa Touch, for example, allows easy navigation from any class to each of its superclasses. If you can’t find what you’re looking for in one class interface or reference, it may very well be defined or documented in a superclass further up the chain.