rootViewController 获取报错 : unrecognized selector sent to instance

项目有替换tabbar图片icon的需求,就在自定义的 UITabBarControllerl 类里定义了一个changeIcon的方法。

发现有时候会报 [UIApplicationRotationFollowingController chanageICONImage:]: unrecognized selector sent to instance 的错误。

项目中用到的方法:

UIWindow *window = [UIApplication sharedApplication].keyWindow;

RootTabBarViewController *tabbarVC = (RootTabBarViewController *)window.rootViewController;

分析了一下,可能是获取不到视图的根控制器,就换了一种方法:

 AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

 RootTabBarViewController *tabbarVC = (RootTabBarViewController *) appdelegate.window.rootViewController;

经过测试问题没有再出现,两种方法都可以获取到rootViewController,但是第二种更稳定一些,不会因为项目中有写弹窗等关系到window视图的操作而影响到获取根视图控制器。另外,为了更加安全,建议加上判断获取到的控制器的类型的方法:

 if ([[appdelegate.window.rootViewController class] isKindOfClass:[RootTabBarViewController class]]) { ....}






猜你喜欢

转载自blog.csdn.net/weixin_41970246/article/details/80176947