总是调用当前类的方法

时间:2012-07-04 09:43:58

标签: objective-c cocoa

@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

有没有办法实现A,所以在A类中[self tmp]内调用[self foo]会导致调用A:foo而不是B:foo

(所以在调用[b foo] == @“B”后调出[b tmp] == @“A”后的输出)

喜欢

@implementation A

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

2 个答案:

答案 0 :(得分:1)

您可以使用super

@implementation B

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

答案 1 :(得分: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
相关问题