1. 程式人生 > >iOS 不支援多繼承,實現多繼承的4種方式

iOS 不支援多繼承,實現多繼承的4種方式

classA 實現了methodA  方法  classB 實現了 methodB 方法   classC 要同時實現methodA和methodB方法 在C++ 中用多繼承就能實現,但是Objective c 不支援多重繼承,那如何實現。

方法1. 組合方式,用ClassC  新增ClassA ,ClassB成員變數 來呼叫methodA,methodB

//定義ClassA以及其methodA

@interface ClassA : NSObject { } -(void)methodA; @end //定義ClassB以及其methodB @interface ClassB : NSObject { } -(void)methodB; @end //定義ClassC以及其需要的methodA,methodB @interface ClassC : NSObject {   ClassA *a;   ClassB *b; } -(id)initWithA:(ClassA *)A b:(ClassB *)B; -(void)methodA; -(void)methodB; @end

//注意在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];

}

方法2.協議protocol  設定ClassA delegate和 ClasssB delegate 以及實現方法ClassA裡的methodA,和ClasssB裡的methodB。ClassC遵守這兩個協議就可以。
方法3.類別  ClassC的類別 可以實現ClassA的methodA和ClassB的methodB兩個方法,這樣ClassC就可以呼叫methodA和methodB 方法4.訊息轉發機制 我們知道objective-c中呼叫方法的方式是發訊息,那如果給一個例項物件發一個未定義的訊息呢?結果就是crash,其實這中間系統給我們第二次機會,就是可以轉發該訊息 如果未調到定義的訊息,runtime會給該例項第二次機會,首先呼叫methodSignatureForSelector 或去方法簽名,然後呼叫forwardInvocation,如果使用者自己定義的類,沒有重寫這兩個方法,即不支援方法轉發
  1. @interface LOCBird : NSObject {  
  2.     NSString* name_;  
  3. }  
  4. @end  
  5. @implementation LOCBird  
  6. - (id)init  
  7. {  
  8.     self = [super init];  
  9.     if (self) {  
  10.         name_ = [[NSString alloc] initWithString:@"I am a Bird!!"];  
  11.     }  
  12.     return self;  
  13. }  
  14. - (void)dealloc  
  15. {  
  16.     [name_  release];  
  17.     [super dealloc];  
  18. }  
  19. - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector  
  20. {  
  21.     NSMethodSignature* signature = [super methodSignatureForSelector:aSelector];  
  22.     if (signature==nil) {  
  23.         signature = [name_ methodSignatureForSelector:aSelector];  
  24.     }  
  25.     NSUInteger argCount = [signature numberOfArguments];  
  26.     for (NSInteger i=0 ; i<argCount ; i++) {  
  27.         NSLog(@"%s" , [signature getArgumentTypeAtIndex:i]);  
  28.     }  
  29.     NSLog(@"returnType:%s ,returnLen:%d" , [signature methodReturnType] , [signature methodReturnLength]);  
  30.     NSLog(@"signature:%@" , signature);  
  31.     return signature;  
  32. }  
  33. - (void)forwardInvocation:(NSInvocation *)anInvocation  
  34. {  
  35.     NSLog(@"forwardInvocation:%@" , anInvocation);  
  36.     SEL seletor = [anInvocation selector];  
  37.     if ([name_ respondsToSelector:seletor]) {  
  38.         [anInvocation invokeWithTarget:name_];  
  39.     }  
  40. }  
  41. @end  
 多繼承訊息轉發原理就是  ClassC 沒法實現methodA 和methodB 但是有成員變數ClassA 實力和ClassB例項。可以在用ClassC呼叫methodA 和methodB方法的時候訊息轉發給對應的例項就不會導致crash。其實和1組合方式類似。 主要參考連結: http://blog.csdn.net/freshforiphone/article/details/7381329

有不對地方歡迎指出