91

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.

3 Answers 3

136

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.

Sign up to request clarification or add additional context in comments.

8 Comments

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 ;)
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?
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.
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/Conceptual/…
|
3

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>

4 Comments

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.
But a subclass of UIViewController can also "support", in this case, singleton pattern should I wish.
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.
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...
-4

Do you know about Protocols, protocols is the way to implement the multiple inheritance

6 Comments

+1 "To capture similarities among classes that are not hierarchically related." developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/…
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.
you can combine protocol with either a category or composition.
-1 because Protocols are not there for multiple inheritance at all. Similarly in JAVA , Interfaces are not to provide or mimic multiple inheritance.
@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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.