Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Classes can have properties that refer to instances of other classes. This is called composition, because you’re combining different kinds of objects together to accomplish a task:
@interface User : NSObject @property char* name; @property char* password; @end @interface Game : NSObject @property User* playerOne; @property User* playerTwo; @property int playerOneScore; @property int playerTwoScore; @property int durationInSeconds; @end
When you want to use methods and properties from another class, but it logically doesn’t make sense to inherit from that class (a camera isn’t a kind of media), you can create a property for the other kind of object instead:
@interface Device : NSObject @property char* name; @property int minFocalDistance; @end @interface Media : NSObject @property int duration; @property char* format; @property Device* recordingDevice; @end
This way, a Media object can use a Device object, but it doesn’t have to be a Device object, which makes much more sense. Cocoa encourages you to use composition much more frequently than subclassing, because subclassing can add complexity, which means it’s harder to create great software.