一丶问题
在多个控制器,跳转之后,想回到rootControl,调用
- (nullable NSArray<__kindof UIViewController *> *)popToRootViewControllerAnimated:(BOOL)animated;
但是rootControl怎么知道是哪个控制来的?
实现思路:
1.delegete
2.notification
3.block
以上是基本思路,但是比较繁琐;
利用hook思想;
在系统调用popToRootViewControllerAnimated之前,把栈最上层的Controller 发给RootControl;
二丶代码实现
思路:
//1.获取实例方法;
class_getInstanceMethod
//2.获取方法实现
method_getImplementation
//3 添加自己的实现block,
注意下id self, SEL _cmd 是oc方法的隐式参数;必填;
imp_implementationWithBlock
添加自己的代码后,必须调用
popToRootIMP(self,_cmd,anima);
不然不会实现跳转;
//4.设置方法实现
method_setImplementation
+(void)load
{
Method popToRootMethod = class_getInstanceMethod([UINavigationController class], @selector(popToRootViewControllerAnimated:));
IMP popToRootIMP = method_getImplementation(popToRootMethod);
IMP customIMP = imp_implementationWithBlock(^(id self, SEL _cmd,BOOL anima){
UINavigationController *nav = self;
UIViewController *toVc = nav.childViewControllers.firstObject;
UIViewController *fromVc = nav.childViewControllers.lastObject;
NSLog(@"我从%@ 来,要到%@去",fromVc,toVc);
popToRootIMP(self,_cmd,anima);
});
method_setImplementation(popToRootMethod, customIMP);
}
之后看Log日志:
我从<ThreeViewController: 0x7fb936c243e0> 来,要到<ViewController: 0x7fb936d0a6a0>去
三丶总结
利用hook思想;
能把复杂的问题瞬间简单化;
像之前的AOP编程,
Runtime的深入使用,才知道Objective-C的强大之处;