Objective-C multiple inheritance

3 Solutions Collect From Internet About “Objective-C multiple inheritance”

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.

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>

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