I'm trying to understand the design principle of composition better. Are there any examples of this in the UIKit or Foundation frameworks?
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/ObjC_classic/index.html
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKit_Framework/
From my experience, and before thinking about this question explicitly, it seems that inheritance is the main pattern for these two frameworks.
Inheritance is rare in Foundation, and is not the primary pattern of UIKit. Composition is much more common in both cases.
The difference between inheritance and composition is often expressed as IS-A versus HAS-A. The IS-A approach to is to subclass. The HAS-A approach is to delegate.
Consider a text field that you would like to only accept certain characters. In an IS-A style, you would subclass UITextField. That's not common in iOS. Instead, you pass a delegate (anything that conforms to <UITextFieldDelegate>) and the text field consults it when needed. This is a HAS-A approach. A text field "has a" delegate.
Consider a UITableView. You would like to make a table of songs. In the IS-A (inheritance) approach, you would subclass UITableView and make a SongsTableView. In the HAS-A (composition) approach, you would create some other object (a SongsDataSource) and give it to a UITableView. In this case, UIKit uses a little of both; you give the UITableView a data source, but that data source is usually (but not required to be) a subclass of UITableViewController.
Similarly, while it is somewhat common to subclass UIView or CALayer, it is also very common to use "stock" views and layers instead and build them up by adding sub-components. This is the HAS-A approach.
Foundation has very little IS-A in it. You very seldom subclass Foundation classes other than NSObject. Consider NSAttributedString. It does not subclass NSString. It has an NSString. This is the usual way of doing things in Foundation. You almost never create your own subclasses of NSString, NSArray, NSDate, NSNumber or any of the other common types out of Foundation. You combine them instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With