如何阻止一个超类方法被调用到一个子类 [英] how to block a superclass method to be called to a subclass

查看:95
本文介绍了如何阻止一个超类方法被调用到一个子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我扩展了一个类的子类的功能,我做一些脏的东西,使超类方法危险(应用程序将挂在一个循环)在子类的上下文。我知道这不是一个天才的想法,但我要去低洼的水果,现在它会给我一些时间。哦,这是一个肮脏的工作,但有人必须这样做。



底线,我需要从外部阻止该方法,或者在直接调用超类时抛出异常。 (但我仍然使用它从子类,除非小心)。



这是最好的方法是什么?



UPDATE ---



所以这是我去的。我不是自我回答,因为Boaz的回答提到了多种有效的方式来做到这一点,这只是适合我的方式。在子类中,我突破了这样的方法:

   - (int)dangerMethod 
{
[ NSException raise:@危险!格式:@不调用直接发送这个方法到这个子类];
return nil;
}

我将此标记为已回答,但显然这并不意味着


解决方案

只要在子类中重新实现不安全的方法,异常或重新实现它是安全的,只要新的实现不调用不安全的超类方法。



对于C ++团队在这里:Objective C doesn不允许你将方法标记为私有。您可以使用其类别系统将界面拆分为单独的文件(从而隐藏私有文件),但类上的所有方法都是公共的。


I'm extending the functionality of a class with a subclass, and I'm doing some dirty stuff that make superclass methods dangerous (app will hang in a loop) in the context of the subclass. I know it's not a genius idea, but I'm going for the low-hanging fruit, right now it's gonna save me some time. Oh it's a dirty job, but someone's gotta do it.

Bottom line, I need to either block that method from outside, or throw an exception when it's called directly to the superclass. (But I still use it from the subclass, except with care).

What would be the best way to do this?

UPDATE ---

So this is what I went for. I'm not self-answering, as Boaz' answer mentions multiple valid ways to do this, this is just the way that suited me. In the subclass, I overrode the method like this:

- (int)dangerousMethod
{
  [NSException raise:@"Danger!" format:@"Do not call send this method directly to this subclass"];
  return nil;
}

I'm marking this as answered, but evidently that doesn't mean it's closed, further suggestions are welcome.

解决方案

Just re-implement the unsafe method in your subclass and have it do nothing or throw an exception or re-implement it as safe, just as long as the new implementation doesn't call the unsafe superclass method.

For the C++ crew in here: Objective C doesn't let you mark methods as private. You can use its category system to split up the interface into separate files (thus hiding 'private' ones), but all methods on a class are public.

这篇关于如何阻止一个超类方法被调用到一个子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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