如何在第二次启动时启动另一个viewController

时间:2015-07-29 18:59:16

标签: ios objective-c

这里是我在viewController.m下的代码

当用户选择viewController

时,将运行此代码
-(void)switchViews {
    UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [mainStory instantiateViewControllerWithIdentifier:schoolName];
    [self presentModalViewController:vc animated:YES];

    NSUserDefaults *defaultViewController = [NSUserDefaults standardUserDefaults];
    [defaultViewController setObject:nil forKey:@"save"];
    [defaultViewController synchronize];

}

此代码将在第二次启动应用时运行

-(void)loadNewView {
    UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    NSUserDefaults *newUserDefault = [NSUserDefaults standardUserDefaults];

    NSString *newVC = [NSString stringWithFormat:@"save", schoolName];
    UIViewController *newViewController = [mainStory instantiateViewControllerWithIdentifier:newVC];
    [self presentModalViewController:newViewController animated:YES];
}

请记住schoolName是一个字符串

如何在viewDidLoad下运行[self loadNewView],但在第二次启动应用时运行它?

3 个答案:

答案 0 :(得分:1)

您应该执行类似

的操作
id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"save"];
if (value) {
   UIViewController *vc = [mainStory instantiateViewControllerWithIdentifier:value];
   [self presentModalViewController:vc animated:YES];
} else {
   // first time logic
}

AppDelegate或您拥有导航逻辑的任何地方。你不应该在viewDidLoad中有这种逻辑。

答案 1 :(得分:0)

-(void)viewDidLoad {
    [super viewDidLoad];

    NSString *launchCount = @"LaunchCount";
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger count;
    if([userDefaults objectForKey:launchCount]) {
        count = [userDefaults integerForKey:launchCount];
    }
    else {
        count = 0;
    }
    count++; //increment the launch count
    [userDefaults setObject:[NSNumber numberWithInt:count] forKey:launchCount];
    [userDefaults synchronize];

    if([userDefaults integerForKey:launchCount] >= 2) {
       // Do your thang
    }
}

答案 2 :(得分:0)

在ViewDidLoad函数上执行类似这样的操作

 if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedFirst"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLauncheFirst"];
        [[NSUserDefaults standardUserDefaults] synchronize];

[self switchViews];
    }
else
{
[[NSUserDefaults standardUserDefaults] setBool:No forKey:@"HasLauncheFirst"];
        [[NSUserDefaults standardUserDefaults] synchronize];

[self loadNewView];
}