开发者

UITabBarController app - how to call method between controllers?

I have what I assum开发者_JS百科e is a very simple problem, but the solution has escaped me. I have a UITabBarController app. There are two views, I'll call them A and B. And of course I have an AppDelegate class that initializes the tab bar.

View B has a button called clearScore:. When it is pressed, view B needs to invoke directly or indirectly clearScore: on view A. Can someone show me the steps to make this happen? Thanks for any help!


You can use Notifications or Key-Value-Observing (KVO).

Let's assume you've got a model object in which your property score resides. Now you add a Key-Value-Observer in you viewController B to the score property of the model instance. When you press clearScore in A you set the score property to 0(or nil). The Observer will inform B that the property changed so you can easily update your view of B.


I think there is a more simple way to achieved that:

You can use something like the below code in bViewController:

for (UIViewController* testViewController in self.tabBarController.viewControllers) {
    if ([testViewController respondsToSelector:@selector(clearScore)]) {
        [(aViewController *)testViewController clearScore];
    }
}

Or:

for (UIViewController* testViewController in self.tabBarController.viewControllers) {
    if ([testViewController isKindOfClass:[aViewController class]]) {
        [(aViewController *)testViewController clearScore];
    }
}

Don't forget to #import "aViewController.h" in bViewController's header;


Views should talk directly only to their own controllers, and a controller shouldn't talk to views other than its own. If one of view controller B's buttons should result in a message being sent to view controller A, then the button should trigger an action in controller B that in turn sends a message to A.

However, -clearScore: sounds like a method that would be part of a model rather than part of a controller, and the fact that B has an interest is further evidence of the same. You might want to think about refactoring your code a bit.


    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    //other codes

    [self.tabBarController setDelegate:self]

    //other codes
    }

// UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    if ([viewController respondsToSelector:@selector(reloadDataTemp)]) {
        [(YourViewController *)viewController reloadData];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜