Multiple inheritance is not supported in Objective-C. The reason for not supporting this mechanism may be the fact that it would be too difficult to include in the language or the authors considered this to be poor programming and design decision. However, in various cases, multiple inheritance is useful. Fortunately, objective C does provide some workarounds for achieving multiple inheritance. The following are the options:
Option 1: Message Forwarding
Forwarding messages, as the name implies, is the mechanism offered by the Objective-C runtime. When a message is passed to an object and the object does not respond to it, the application crashes. But before the crash, the c runtime target provides a second chance for the program to pass the message to the corresponding object / class that actually responds to it. After tracking the message to the topmost superclass, the forwardInvocation message is forwardInvocation . By overriding this method, you can actually redirect the message to another class.
Example. If there is a Car class that has a carInfo property that provides the car brand, model and year of manufacture, and carInfo contains data in NSString format, it would be very useful if the methods of the NSString class could be called on objects of the Car class, which themselves actually inherited from NSObject.
- (id)forwardingTargetForSelector:(SEL)sel { if ([self.carInfo respondsToSelector:sel]) return self.carInfo; return nil; }
Source: iOS 4 Developer Cookbook - Erica Sadun
Option 2: Composition
Composition is a cocoa design template that includes binding to another object and calling its functions when required. Composition is actually a method for a presentation based on several other views. Thus, in cocoa terminology, this is very similar to subclassification.
@interface ClassA : NSObject { } -(void)methodA; @end @interface ClassB : NSObject { } -(void)methodB; @end @interface MyClass : NSObject { ClassA *a; ClassB *b; } -(id)initWithA:(ClassA *)anA b:(ClassB *)aB; -(void)methodA; -(void)methodB; @end
Source: Objective-C Multiple Inheritance
Option 3: Protocols
Protocols are classes that contain a method that will be implemented by other classes that implement the protocol. One class can implement as many protocols as it can and implement methods. However, with protocols, only methods can be inherited, not instance variables.