目标-c:在基类上调用[自身消息]正在调用后代方法 [英] Objective-c: Calling [self message] on a base class is invoking the descendant method

查看:70
本文介绍了目标-c:在基类上调用[自身消息]正在调用后代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习此方法,很抱歉,如果该方法有一些我仍然无法掌握的解决方案.

I just started learning this, so sorry if this has some obvious solution I still can't grasp.

我有这两节课:

@implementation Person
-(void)saySomething:(NSString*) something {
    NSLog(@"%@",something);
}
-(void)yellSomething:(NSString*) something {
    [self saySomething:[something uppercaseString]];
}
@end

@implementation ShoutingPerson : Person

-(void)saySomething:(NSString*)something {
    [super yellSomething:something];
}

@end

这会导致循环引用调用,因为在后代类上始终会始终调用.

This is causing a circular reference call because saySomething is always being called on the descendant class.

如何使yellSomethingPerson类而不是后代类上调用saySomething方法?

How can I make yellSomething invoke the saySomething method on Person class instead of the descendant class ?

推荐答案

正如乔纳森(Jonathan)所说,您真的应该尽可能避免这种情况.需要此功能只是一个糟糕的设计.如果打算将您的基类作为子类,则其文档应说明哪些方法必须被覆盖,哪些其他方法 被覆盖. 请勿禁止其他任何操作,以避免出现此类问题.

As Jonathan says, you really should avoid this if at all possible. It's just a bad design to need this functionality. If your base class is intended to be subclassed, its documentation should spell out which methods must be overridden and which others may be overridden. Anything else should not be overridden, to avoid problems like this.

也就是说,如果您处于非常特殊的情况下有必要(也许您无法使用无法重构的第三方代码),这是有可能的.但这并不漂亮.您需要致电 objc_msgSendSuper_stret #//apple_ref/doc/uid/TP40001418-CH3g-BBCFBBGA>结构objc_super 指向selfYourBaseClass.

That said, if you are in a very unusual situation where it is necessary (perhaps you're stuck working with 3rd party code that you cannot refactor), it is possible. But it's not pretty. You need to call objc_msgSendSuper or objc_msgSendSuper_stret manually, after constructing an instance of struct objc_super pointing to self and YourBaseClass.

请注意,如果您来自C ++,则默认行为是相同的-如果您从基类中调用SomeFunction()并且它是一个虚拟方法,则将执行子类的替代.您必须在呼叫之前加上前缀,以明确说明该类,例如MyBaseClass::SomeFunction().在Objective-C中没有直接的等效项-我要说,因为通常这是个坏主意.

Note that if you're coming from C++ the default behaviour there is the same - if you call SomeFunction() from your base class and it's a virtual method, the subclass's override will be executed. You would have to prefix your call to spell out the class explicitly, e.g. MyBaseClass::SomeFunction(). There's no direct equivalent for that in Objective-C - I'd say because it's just such a bad idea generally.

这篇关于目标-c:在基类上调用[自身消息]正在调用后代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆