在 Objective-C 中使用类别覆盖方法 [英] Overriding methods using categories in Objective-C

查看:33
本文介绍了在 Objective-C 中使用类别覆盖方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用类类别来覆盖已经使用类别实现的方法吗?像这样:

Can I use a class category to override a method that is already implemented using a category? Like this:

1) 原始方法

-(BOOL) method {
  return true;
}

2) 重载方法

-(BOOL) method {
  NSLog(@"error?"); 
  return true; 
}

这行得通,还是违法?

推荐答案

来自 Apple 文档:

尽管 Objective-C 语言目前允许您使用类别来覆盖类继承的方法,甚至是在类接口中声明的方法,但强烈建议您不要这样做.类别不能替代子类别.使用类别覆盖方法有几个明显的缺点:

Although the Objective-C language currently allows you to use a category to override methods the class inherits, or even methods declared in the class interface, you are strongly discouraged from doing so. A category is not a substitute for a subclass. There are several significant shortcomings to using a category to override methods:

  • 当类别覆盖继承的方法,类别中的方法可以像往常一样调用继承的通过给 super 的消息实现.但是,如果一个类别覆盖了一个类别中存在的方法类,没有办法调用原始实现.

  • When a category overrides an inherited method, the method in the category can, as usual, invoke the inherited implementation via a message to super. However, if a category overrides a method that exists in the category's class, there is no way to invoke the original implementation.

一个类别不能可靠地覆盖在同一类的另一个类别中声明的方法.

这个问题特别重要,因为许多 Cocoa 类都是使用类别实现的.您尝试覆盖的框架定义的方法本身可能已在类别中实现,因此未定义哪个实现优先.

This issue is of particular significance because many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.

某些类别方法的存在可能会导致所有框架的行为发生变化.例如,如果您在 NSObject 的类别中重写 windowWillClose: 委托方法,则程序中的所有窗口委托都将使用该类别方法进行响应;您的所有 NSWindow 实例的行为可能会改变.您在框架类中添加的类别可能会导致行为发生神秘变化并导致崩溃.

The very presence of some category methods may cause behavior changes across all frameworks. For example, if you override the windowWillClose: delegate method in a category on NSObject, all window delegates in your program then respond using the category method; the behavior of all your instances of NSWindow may change. Categories you add on a framework class may cause mysterious changes in behavior and lead to crashes.

这篇关于在 Objective-C 中使用类别覆盖方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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