警告: Category is implementing a method which will also be implemented by its primary class

    xiaoxiao2021-03-25  69

    警告

    Category is implementing a method which will also be implemented by its primary class

    这个警告的意思是, 在category中重写了原类的方法

    分析

    A category allows you to add new methods to an existing class. If you want to reimplement a method that already exists in the class, you typically create a subclass instead of a category.

    苹果官方文档Customizing existing classes中如下描述:

    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.

    这个警告说明, 类目中添加的这个方法和原类的方法名一致, 运行的时候会执行这个方法, 而且也会执行原类中的方法. 苹果官方文档中又说明,如果在类别中声明的方法的名称与原始类中的方法相同,或者在同一类(或甚至超类)上的另一类中的方法相同,那么该行为对于使用哪种方法实现是未定义的运行。 如果您使用自己的类使用类别,那么这不太可能成为问题,但是在使用类别添加标准Cocoa或Cocoa Touch类的方法时可能会导致问题。

    解决方案

    用继承的方式重写父类方法用类目重写原类的方法, 需要通过runtime的method swizzling来进行方法IMP的交换处理.忽略警告处理 1>代码方式 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation" // your override #pragma clang diagnostic pop

    2>Xcode设置方式: 在target的 build settings下 搜索other warning flags 然后给其添加 -Wno-objc-protocol-method-implementation

    注: 这里的警告忽略的处理方法不能改变原警告造成的问题, 只能是屏蔽掉了警告, 所以当前方法和原类的方法都还是会执行的.

    拓展

    在忽略警告的处理上, 你可以在项目运行的时候, 右键警告选择 reveal in log 就可以在警告详情中发现 -Wobjc-protocol-method-implementation 这么一个格式的字段 在-W后添加一个no- ,然后添加到 other warning flags 中 就可以忽略你这些警告了.

    参考资料: Suppress warning “Category is implementing a method which will also be implemented by its primary class”

    转载请注明原文地址: https://ju.6miu.com/read-53316.html

    最新回复(0)