简体   繁体   中英

How do I call method in current view controller of tabbar controller?

@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    UITabBarController *tabBarCtrl; 
}
@end

@interface FirstViewController : UIViewController {
}
-(void)myMethod;
@end

I want to call myMethod in FirstViewControlle.m from MyAppDelegate.m. I tried this.

[self.tabBarCtrl.selectedViewController myMethod];

Compiler says "UIViewController may not respond to myMethod". How do I call FirstViewController's method?

You cast it so the compiler knows the exact type. (you have to be very certain and/or check on runtime if the object actually is that type)

[(FirstViewController*) self.tabBarCtrl.selectedViewController myMethod];

Should do it.

And please, compile with "Warnings as errors". This will help you improve your skills, by forcing you to "solve" all warnings. And I think you have a lot to learn still ;-)

Well since you are calling a method on UIViewController Obj-C can't assure that the method exists. You could just check if the methods exsist:

if([self.tabBarCtrl.selectedViewController repondsToSelector:@selector(myMethod)]) {
  [self.tabBarCtrl.selectedViewController performSelector:@selector(myMethod)];
}

This ways allows you to create the myMethod on more then just FirstViewController

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM