Objective-C multiple inheritance

72,919

Solution 1

Objective-C doesn't support multiple inheritance, and you don't need it. Use composition:

@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

Now you just need to invoke the method on the relevant ivar. It's more code, but there just isn't multiple inheritance as a language feature in objective-C.

Solution 2

This is how I code singletonPattern as "a parent" Basically I used a combination of protocol and category.

The only thing I cannot add is a new "ivar" however, I can push it with associated object.

#import <Foundation/Foundation.h>
@protocol BGSuperSingleton
+(id) singleton1;
+(instancetype)singleton;
@end

@interface NSObject (singleton) <BGSuperSingleton>

@end

static NSMutableDictionary * allTheSingletons;

+(instancetype)singleton
{
    return [self singleton1];
}
+(id) singleton1
{
    NSString* className = NSStringFromClass([self class]);

    if (!allTheSingletons)
    {
        allTheSingletons = NSMutableDictionary.dictionary;
    }

    id result = allTheSingletons[className];

    //PO(result);
    if (result==nil)
    {
        result = [[[self class] alloc]init];
        allTheSingletons[className]=result;
        [result additionalInitialization];
    }
    return result;
}

-(void) additionalInitialization
{

}

Whenever I want a class to "inherit" this BGSuperSingleton I just do:

#import "NSObject+singleton.h"

and add @interface MyNewClass () <BGSuperSingleton>

Share:
72,919
Dilshan
Author by

Dilshan

Updated on July 10, 2022

Comments

  • Dilshan
    Dilshan almost 2 years

    I have 2 classes one includes methodA and the other include methodB. So in a new class I need to override the methods methodA and methodB. So how do I achieve multiple inheritance in objective C? I am little bit confused with the syntax.

  • d11wtq
    d11wtq over 13 years
    Composition is very often a better approach to take than inheritance, especially if you do much unit testing on the code. It affords much more flexibility in that you can easily swap out the implementations without redefining the class itself. Particularly handy when you want to, say, swap ClassA and ClassB for mock objects. Even at runtime swapping out implementations (e.g. FTPFileStore vs LocalFileStore) becomes cleaner with composition. That doesn't mean inheritance doesn't have it's place though, but the need for multiple inheritance would suggest that I re-think my design ;)
  • Trần Trung Hiếu
    Trần Trung Hiếu over 12 years
    +1 "To capture similarities among classes that are not hierarchically related." developer.apple.com/library/mac/#documentation/Cocoa/Concept‌​ual/…
  • jake_hetfield
    jake_hetfield about 12 years
    In this case, where both methods will be overridden, protocols will do the trick. In other cases when you want to use inheritance to reuse code, protocols would not help. However this can usually be solved by letting the classes superclasses inherit from each other, or by combining them, there is usually a way to get it right if a subclass actually share code with 2 classes.
  • Lloyd Sargent
    Lloyd Sargent about 11 years
    Categories are not multiple inheritance. They're a way of tacking on methods/functions to an already existing class. Multiple inheritance allows a third class to be a combination of one OR MORE classes (including variables). I like categories. Categories are very useful. But they are NOT multiple inheritance.
  • Septiadi Agus
    Septiadi Agus about 11 years
    you can combine protocol with either a category or composition.
  • Septiadi Agus
    Septiadi Agus about 11 years
    But a subclass of UIViewController can also "support", in this case, singleton pattern should I wish.
  • Septiadi Agus
    Septiadi Agus about 11 years
    Technically all NSManagedObject "can now call" [obj singleton]. I set those I wish with support of the protocol. As good as multiple inheritance in anyway. This is only if I want to the child class to support both the interface and implementation of the parent. If only the implementation then obviously composition is the way to go.
  • zakdances
    zakdances almost 11 years
    I don't understand this. Don't you need to instantiate ClassA and ClassB? Does calling methodA: on MyClass somehow automatically call methodA: on ClassA?
  • d11wtq
    d11wtq almost 11 years
    No, but you can still share the behaviour through message-passing, the way OOP was originally supposed to work. If you don't immediately jump to thinking you need inheritance and instead consider a solution using composition, you'll find you start structuring your programs in a more maintainable way. Of course ObjC has basic inheritance for the cases where it is correct to use it.
  • ashokdy
    ashokdy over 10 years
  • arsenius
    arsenius over 10 years
    d11wtq, great answer! As an addition, message forwarding allows you to skip the step of re-implementing methodA and methodB. Messages can be automatically forwarded to appropriate objects with just a little work. developer.apple.com/library/mac/documentation/Cocoa/Conceptu‌​al/…
  • thesummersign
    thesummersign about 9 years
    -1 because Protocols are not there for multiple inheritance at all. Similarly in JAVA , Interfaces are not to provide or mimic multiple inheritance.
  • ghr
    ghr over 8 years
    @ashokdy: there are too many errors in the referenced article: it talks about obj-c having Multiple inheritance, its example on the second page asks us to 'Consider a base class Shape and its derived class Rectangle as follows' but the example is about Person and Employee.
  • CommaToast
    CommaToast over 8 years
    Just adding the protocol like <BGSuperSingleton> does not make the classes then be able to call the "singleton" method. You still have to implement it...
  • CommaToast
    CommaToast over 8 years
    Protocols do have the benefit of allowing you to let Objective C runtime know that something responds to a given selector and to make the compiler prevent you from failing to implement a callback method that needs to be there for things to work correctly—without having to depend on (i.e. import/include) whatever's on the other side of the protocol. They are basically a thin facade that doesn't even exist :D
  • mfaani
    mfaani about 8 years
    @FreeAsInBeer From Apple's own documentation A protocol declares a programmatic interface that any class may choose to implement. Protocols make it possible for two classes distantly related by inheritance to communicate with each other to accomplish a certain goal. They thus offer an alternative to subclassing. As you can see Apple is explicitly using subclassing ie inheriting. Perhaps Nikesh including this in his own answer would be helpful to clarify his argument
  • rezwits
    rezwits almost 8 years
    I don't see why you need to include: -(void)methodA; -(void)methodB; Because wouldn't you just invoke them on the class A when needed and then on class B when needed, and add them as Properties? I would think this would be a better approach, seeing as, one of the benefits of subclassing is NOT having to put the method declaration in the subClass.
  • Will
    Will almost 5 years
    Composition is very handy!