1

I have the subclass Foo of the class Bar:

@interface Foo : Bar
{ 
- (void)methodName;
}

It has the methodName method which overrides the Bar class' method.

I have the object of the Foo's superclass:

Bar *bar = [[Bar alloc] init];

Then I send the message to this object:

[bar methodName];

Why is the Foo's implementation of the methodName is executed instead of the Bar's? This method's implementation in Foo completely overrides the one in Bar, it doesn't call [super methodName]. Pretty obvious to me that if the object were of the subclass, the subclass' implementation would be called, but why is it executed when the message is sent to the object of superclass?

Thank you in advance.

4

2 回答 2

5

不应该。您可能想在[bar class]之前尝试调用[bar methodName]以确保您确实拥有 Bar 的实例。如果它真的是 Bar 的一个实例,我想不出它可能会调用 Foo 子类的方法。

于 2013-08-21T20:22:22.373 回答
2

您可能在代码中遗漏了一些小细节。被覆盖的方法只会在覆盖它的类的对象上被调用。你不打电话给[super method]Foo吗?这是一个示例代码:

@interface Bar : NSObject
-(void)method;
@end

@implementation Bar
-(void)method {
    NSLog(@"Bar");
}
@end

@interface Foo : Bar
@end

@implementation Foo
// override method
-(void)method {
    NSLog(@"Foo");
}
@end

调用它们:

[[[Bar alloc] init] method]; // writes Bar
[[[Foo alloc] init] method]; // writes Foo
于 2013-08-21T20:33:33.930 回答