Http://www.cnblogs.com/ygm900/archive/2013/01/16/2862678.html
We all know that Objective C cannot support multiple inheritance like C + +, but the use of OC often encounters situations where multiple inheritance is required. For example, there are MethodB in Methoda,classb in ClassA, and now you need to use the methods in these two classes. How to follow the programming ideas of C + +, there is no doubt that the adoption of multi-inheritance is done, in OC need to move the brain.
In fact, when we learn design patterns, we know that the efficiency of multiple inheritance is not high, and the combination of patterns can completely replace the inheritance model. Well, this idea can be used to achieve multiple inheritance in OC (perhaps OC discards multiple inheritance, that is, forcing us to use a more efficient combination of design patterns!). )。 The following is the actual code to represent how the combination replaces multiple inheritance.
Now CLASSC need to inherit ClassA in MethodA, ClassB MethodB, the specific code implementation is:
Define ClassA and its MethodA
@interface Classa:nsobject {
}
-(void) MethodA;
@end
Define CLASSB and its METHODB
@interface Classb:nsobject {
}
-(void) MethodB;
@end
Define the CLASSC and the methoda,methodb it needs
@interface Classc:nsobject {
ClassA *a;
ClassB *b;
}
-(ID) Initwitha: (ClassA *) A B: (ClassB *) b;
-(void) MethodA;
-(void) MethodB;
@end
Note the implementation of the CLASSC
@implementation ClassC
-(ID) Initwitha: (ClassA *) A B: (ClassB *) b{
A=[[classa alloc] initwithclassa:a];//[a copy];
B=[[CLASSB alloc] initwithclassb:b];//[b copy];
}
-(void) methoda{
[A MethodA];
}
-(void) methodb{
[B MethodB];
}
The above is a combination of the way to achieve the multi-inheritance function, to solve the OC can not inherit more syntax. So is there another way to implement multiple inheritance?
Although OC is syntactically forbidden to use multiple inheritance for classes, multiple inheritance is allowed in compliance with the Protocol. So you can use protocols to achieve multiple inheritance. But the protocol can only provide the interface, and not provide the implementation way, if only want to inherit the base class interface, then abide by the multi-protocol is undoubtedly the best method, and not only need to inherit the interface, but also inherit its implementation, then the protocol is powerless. Multi-Protocol compliance is relatively simple, the specific implementation of the way here will not talk about
Implementation of OBJECTIVE-C Multiple inheritance