目标 c 多重继承

我有两个类,一个包括 methodA,另一个包括 methodB。因此,在一个新的类中,我需要重写 methodA 和 methodB 方法。那么我怎样才能达到目标 c 的多重继承呢?我对语法有点困惑。

74178 次浏览

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.

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

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>