gpt4 book ai didi

objective-c - 在类别中重写并在子类中再次重写的方法的调用优先级

转载 作者:太空狗 更新时间:2023-10-30 03:50:27 26 4
gpt4 key购买 nike

我正在使用 Objective-C 开发一个项目,我遇到了一个情况。

假设我有一个名为 Foo 的类。我为这个名为 Foo+Bar 的类实现了一个类别,并覆盖了 Foo 的方法 fooMethod:

然后我为 Foo 创建了一个名为 Baz 的子类,并覆盖了这个类中相同的 fooMethod:

  1. 当我在 Baz 对象上使用方法 fooMethod: 时,实现将被调用? Foo+BarBaz 里面的一个?
  2. Objective-C 如何处理这种情况,为什么?

我愿意接受任何好的解释和/或文档。

最佳答案

如果您重写类别中的方法,则行为明确为 undefined .所以请不要:

If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime.

如果您要重写在父类(super class)的类别中一次 定义的方法,那么当然会调用子类实现。

但是在这里您覆盖了在父类(super class)中定义两次的方法。行为很可能是未定义的,因为您覆盖了未定义的实现。即使这行得通,也无论如何都是糟糕的代码。

真的,请不要这样做。

关于objective-c - 在类别中重写并在子类中再次重写的方法的调用优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com