在切换tabBarController索引而不是segueing时,将数据从一个ViewController传递到另一个ViewController

时间:2014-10-20 20:13:07

标签: ios objective-c uitabbarcontroller

我的应用包含一个带有两个标签的tabBarController。标签号0包含SearchViewController,标签号1包含MatchCenterViewController。我想要做的是在切换到该选项卡之前设置MatchCenterViewController s didAddNewItem属性的值。我知道,如果我用segue做了这个,那就这样做了:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"ShowMatchCenterSegue"]) {
        MatchCenterViewController *controller = (MatchCenterViewController *) segue.destinationViewController;

        self.didAddNewItem = 1;
        controller.didAddNewItem = self.didAddNewItem;
    }
}

但是我不想用segue执行此操作,我希望在调用didAddNewItem之前设置MatchCenterViewController [self.tabBarController setSelectedIndex:1];。是否有可能做到这一点?

2 个答案:

答案 0 :(得分:1)

您应该可以从[self.tabBarController viewControllers]

中提取视图控制器

一些伪代码供你尝试和搞乱:

UIViewController *toViewController = [self.tabBarController viewControllers][1];
if ([toViewController isKindOfClass:[MatchCenterViewController class]]) { // This is just for the sake of safety. Good practice to get into type checking before you cast.
    MatchCenterViewController *matchViewController = (MatchCenterViewController *)toViewController;
    matchViewController.didAddNewItem = true; // Really this should be a Bool!
}
[self.tabBarController setSelectedIndex:1];

答案 1 :(得分:0)

最好使用协议和委托,这是将此数据传递给另一个视图控制器的最简洁方法。它还将您的代码分离,以便以后更容易管理。例如,您构建的iPad版本没有UITabbarController。

Define a protocol in SearchViewController.h:

//under the #import
@protocol SearchViewControllerDelegate

//define a property to send delegate messages to
@property (nonatomic,strong) id <SearchViewControllerDelegate> delegate;

//after @end
@protocol SearchViewControllerDelegate <NSObject>
- (void)searchViewControllerDidSearchWithResult:(NSArray *)result;

Then when you are setting up the view controllers assign MatchViewController to be the SearchViewControllers delegate.

//in SearchViewController.m send the delegate message
[self.delegate searchViewControllerDidSearchWithResult:arr];

Then in MatchViewController adopt the protocol to get messages.