Objective-C multiple inheritance

Objective CInheritanceMultiple Inheritance

Objective C Problem Overview


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.

Objective C Solutions


Solution 1 - Objective C

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 - Objective C

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>

Solution 3 - Objective C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDilshanView Question on Stackoverflow
Solution 1 - Objective Cd11wtqView Answer on Stackoverflow
Solution 2 - Objective CSeptiadi AgusView Answer on Stackoverflow
Solution 3 - Objective CNikesh KView Answer on Stackoverflow