从NSObject类推送iOS UIViewController

时间:2014-06-22 19:25:02

标签: ios uiviewcontroller uinavigationcontroller nsobject

我的AppDelegate中有以下代码。它在In App Purchase到期检查期间使用,如果订阅即将到期,将显示一个弹出窗口供用户选择续订,如果有,它会将In App Purchase的视图控制器推送到堆栈。

我想将代码从AppDelegate中移出,并转移到自己的NSObject类中(仅用于整洁)。但是,如何调用从另一个类推送View Controller?

self.window.rootViewController并不存在于NSObject类中,所以当然不会起作用。

UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
            UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
            UICollectionViewController *ivc = (UICollectionViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"IAPViewController"];
            [navigationController pushViewController:ivc animated:YES];

2 个答案:

答案 0 :(得分:1)

在您的NSObject类中,当您想要推送vc时,通过NSNotificationCenter发布通知:

[[NSNotificationCenter defaultCenter] postNotificationWithName:@"PushMyViewControllerNote" object:nil];

在AppDelegate.m中注册观察者:

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


    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(handlePushVCNotification:)        
                                                 name:@"PushMyViewControllerNote" 
                                               object:nil]; 
    //...
    return YES;
}

//...
- (void)handlePushVCNotification:(NSNotification *)note
{ 
    // First you must find currently visible view controller
    // for how to do it, find it yourself :)
    // but you can check https://gist.github.com/snikch/3661188
    UIViewController *visibleVC = [self findVisibleVC];
    UINavigationController *nc = visibleVC.navigationController;
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
    UICollectionViewController *ivc = (UICollectionViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"IAPViewController"];
    [nc pushViewController:ivc animated:YES];
}

答案 1 :(得分:1)

你应该做的是创建一个继承自NSObject的独立类。称之为AppPurchase。然后,将AppPurchase类导入到您的app委托中。至于推送视图控制器,该代码应该与AppPurchase类分开。

AppPurchase类是模型的一部分,不应该负责推送视图控制器。如果AppPurchase实例中的数据发生更改,则控制器可以采取一些操作并更改您的视图。

您应该了解有关MVC或模型 - 视图 - 控制器的更多信息。