gpt4 book ai didi

objective-c - 在 Objective-C 中使用类别覆盖方法

转载 作者:IT老高 更新时间:2023-10-28 11:21:19 25 4
gpt4 key购买 nike

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

1) 原始方法

-(BOOL) method {
return true;
}

2) 重写方法

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

这行得通,还是违法?

最佳答案

来自 Apple documentation :

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:

  • 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.

  • A category cannot reliably override methods declared in another category of the same class.

    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.

  • 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 - 在 Objective-C 中使用类别覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5272451/

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