iOS 不支援多繼承,實現多繼承的4種方式
阿新 • • 發佈:2018-12-26
classA 實現了methodA 方法 classB 實現了 methodB 方法 classC 要同時實現methodA和methodB方法 在C++ 中用多繼承就能實現,但是Objective c 不支援多重繼承,那如何實現。
方法1. 組合方式,用ClassC 新增ClassA ,ClassB成員變數 來呼叫methodA,methodB
//定義ClassA以及其methodA
//注意在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];
[b methodB];
}
方法2.協議protocol 設定ClassA delegate和 ClasssB delegate 以及實現方法ClassA裡的methodA,和ClasssB裡的methodB。ClassC遵守這兩個協議就可以。- @interface LOCBird : NSObject {
- NSString* name_;
- }
- @end
- @implementation LOCBird
- - (id)init
- {
- self = [super init];
- if (self) {
- name_ = [[NSString alloc] initWithString:@"I am a Bird!!"];
- }
- return self;
- }
- - (void)dealloc
- {
- [name_ release];
- [super dealloc];
- }
- - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
- {
- NSMethodSignature* signature = [super methodSignatureForSelector:aSelector];
- if (signature==nil) {
- signature = [name_ methodSignatureForSelector:aSelector];
- }
- NSUInteger argCount = [signature numberOfArguments];
- for (NSInteger i=0 ; i<argCount ; i++) {
- NSLog(@"%s" , [signature getArgumentTypeAtIndex:i]);
- }
- NSLog(@"returnType:%s ,returnLen:%d" , [signature methodReturnType] , [signature methodReturnLength]);
- NSLog(@"signature:%@" , signature);
- return signature;
- }
- - (void)forwardInvocation:(NSInvocation *)anInvocation
- {
- NSLog(@"forwardInvocation:%@" , anInvocation);
- SEL seletor = [anInvocation selector];
- if ([name_ respondsToSelector:seletor]) {
- [anInvocation invokeWithTarget:name_];
- }
- }
- @end
有不對地方歡迎指出