2012-07-04 38 views
3
@interface A : NSObject 

- (void) tmp; 
- (void) foo; 

@end 

@implementation A 

- (void) tmp { 
    [self foo]; 
} 

- (void) foo { 
    NSLog(@"A"); 
} 

@end 

派生類總是調用當前類的方法

@interface B : A 

- (void) foo; 

@end 

@implementation B 

- (void) foo { 
    NSLog(@"B"); 
} 

@end 

代碼

B * b = [[B alloc] init]; 
[b tmp]; // -> writes out B 

是那裏實現的方式,因此內爲[自FOO]呼叫[自TMP]在A級會導致呼叫A:foo不是B:foo

(所以輸出後調用[b foo] == @「B」並在調用後[B TMP] == @ 「A」)

水木清華像

@implementation A 

- (void) tmp { 
    [ALWAYS_CALL_ON_A foo]; 
} 

回答

1

您可以使用super

@implementation B 

- (void) tmp { 
    [super foo]; 
} 
@end 
+0

着這個可以不進行超?與Parag Bafna相似,但只使用類方法? –

+0

使用'super'有什麼問題? –

+1

如果你只是在'B'中省略'tmp'的定義,你會得到同樣的效果。 @PeterLapisu你問的是一個非虛擬的方法。 Objective-C沒有這些(但是C++)。 – echristopherson

0

使用類方法

@interface A : NSObject { 

} 
- (void) tmp; 
+ (void) foo; 
@end 

@implementation A 
- (void) tmp { 
    [A foo]; 
} 

+ (void) foo { 
    NSLog(@"A"); 
} 
@end 
#import "A.h" 
@interface B : A { 

} 
+ (void) foo; 
@end 

@implementation B 
+ (void) foo { 
    NSLog(@"B"); 
} 

@end 
+0

usecase - 我不能使用類方法...可以像這樣的事情用實例方法來完成嗎? –

相關問題