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

警告

这里写图片描述

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类的方法时可能会导致问题。

解决方案

  1. 用继承的方式重写父类方法
  2. 用类目重写原类的方法, 需要通过runtime的method swizzling来进行方法IMP的交换处理.
  3. 忽略警告处理
    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”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值