Objective-C multiple inheritance

I have 2 classes, one includes method A and the other includes method B. Therefore, in the new class, I need to redefine the methods methodA and methodB. So how do I achieve multiple inheritance in objective C? I am a bit confused with the syntax.

+85
inheritance objective-c multiple-inheritance
Nov 16 '10 at 8:16
source share
3 answers

Objective-C does not support multiple inheritance, and you do not 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 call the method on the appropriate ivar. This is more code, but there is simply no multiple inheritance as a language function in objective-C.

+126
Nov 16 2018-10-11T00:
source share

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

The only thing I can’t add is the new β€œivar”, however I can click it using the linked 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 the class to "inherit" this BGSuperSingleton, I just do:

 #import "NSObject+singleton.h" 

and add @interface MyNewClass () <BGSuperSingleton>

+3
Apr 22 '13 at 10:14
source share

Do you know about protocols, protocols are a way to implement multiple inheritance

-2
Jun 04 2018-11-11T00: 00Z
source share



All Articles