软件测试之SDK开发(ios)——分类方法中调用主类的同名原方法

最近在开发ios sdk的时候,sdk的rootViewController是UITabBarController,但是在接入实际app的时候,发现UITabBar消失了。经过调试发现,原来app实现了UITabBar分类的addSubView方法,如下所示:

@implementation UITabBar (Custom)

(void)addSubview:(UIView *)view
{
	if (view.tag != TABBARVIEW_TAG) {
	return;
}

[super addSubview:view];
}

在实际的app中,绝大多数的rootViewController都是UITabBarController,比如微信、qq。为了实现各种各样好看的效果,红点逻辑、消息提醒等等,都会重写UITabBar。

问题找到了,怎么解决呢?

最开始的想法是可不可以不掉用分类覆写的方法,指定调用主类的原方法,经过一番查找发现:
1、如果是类方法,因为分类并没有覆盖主类的同名方法,只是Category的方法排在方法列表前面,而主类的方法被移到了方法列表的后面。 我们可以利用Runtime提供的API,从方法列表里拿回原方法,从而调用。如下所示

-(void) exchangeMainCategoryMethod:(id)target selector:(SEL)selector{
    // Get the class method list
    uint count;
    Method *methodList = class_copyMethodList([target class], &count);
    
    Method firstMethod = nil ;
    Method lastMethod = nil ;
    for (int i = 0; i < count; i++) {
        Method method = methodList[i];
        NSLog(@"Category catch selector : %d %@", i, NSStringFromSelector(method_getName(method)));
        SEL name = method_getName(method);
        if (name == selector) {
            if(!firstMethod){
                firstMethod = method ;
                lastMethod = method ;
            }else{
                lastMethod = method ;
            }
        }
    }
    if(firstMethod && lastMethod && firstMethod!=lastMethod){
        method_exchangeImplementations(firstMethod, lastMethod) ;
    }
}

在调用方法前,先将主类和分类的IMP交换,将主类的IMP放在前面,分类的IMP放在后面,就会优先执行主类的方法。方法调用完后,再将主类和分类的IMP交换,恢复初始的IMP顺序。

2、如果是实例方法,分类同名方法会覆盖主类的方法,获取到的IMP永远是一个,所以只能调用分类的方法,没有办法解决

所以最终只能修改SDK的rootViewController为UINavigationController,从而避开这个问题。

参考文章:
1、https://blog.csdn.net/WOTors/article/details/52576433
2、https://juejin.im/post/5cef42e7518825475e1ad86d
3、https://www.jianshu.com/p/6a3672b8be40
4、https://www.jianshu.com/p/5e659040f85b

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值