开发者

Objective-C multiple inheritance

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 obj开发者_如何学Cective C? I am little bit confused with the syntax.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜