视图控制器不会以编程方式返回到先前的视图控制器

时间:2014-11-17 16:41:21

标签: ios objective-c xcode5

该场景是应用程序首次加载(控制器A加载)时,它会检查是否存在NSDefaultuser。如果它不存在则将其发送给(控制器B)。在控制器B中,用户输入他/她的用户名然后单击确定。现在,NSDefault正在保存用户名,它还应该将其重定向回主视图控制器。这是代码:

if([Username.text  isEqual: @""]) {
    [self showOkAlert:@"Username required"];
}
else if([Password.text isEqual:@""]) {
    [self showOkAlert:@"Password required"];
}
else  {
    //suppose that login was successfully.
    [self SaveCredentials];


    NSString * storyboardName = @"MainStoryboard";
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
    UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"LatestNews"];
    [self presentViewController:vc animated:YES completion:nil];

}

控制器A:

- (void)LoadCredentials {
//load username
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *username = [defaults objectForKey:@"User"];

if(!username) {

    [self showAlert:@"user does not exist"];

    [self dismissViewControllerAnimated:YES completion:nil];

    NSString * storyboardName = @"MainStoryboard";
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
    UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"Login"];
    [self presentViewController:vc animated:YES completion:nil];

}else{
    [self showAlert:@"user exists"]; 
    // for testing purposes I want it to reset when user logged in. Just so I know it resets. Later this method will be called from logout button.
    [self resetUsernameWhenLogout];       
}
}
-(void)resetUsernameWhenLogout {
//reset username when logout
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults]     dictionaryRepresentation];
for (NSString *key in [defaultsDictionary allKeys]) {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)viewDidLoad
{
    [self LoadCredentials];
}

1 个答案:

答案 0 :(得分:0)

这里有几种可能性;首先,iOS8似乎比iOS7更早地实例化VC,因此在viewDidLoad中导航树不完整,你应该只使用viewDidLoad进行附加初始化。尝试移动代码[self LoadCredentials]; 查看WillAppear。

其次,如果您有导航控制器,则应该通过导航控制器将新VC添加到导航树中。如果是这种情况,请尝试以下代码。

  if([Username.text  isEqual: @""]) {
      [self showOkAlert:@"Username required"];
  }
  else if([Password.text isEqual:@""]) {
      [self showOkAlert:@"Password required"];
  }
  else  {
      //suppose that login was successfully.
      [self SaveCredentials];

     //This does not work - I receive a thread error not sure how to debug it 
      UIStoryboard *storyBoard = self.storyboard;
      UIViewController *targetViewController = [storyBoard instantiateViewControllerWithIdentifier:@"LatestNews"];
      UINavigationController *navController = self.navigationController;
    if (navController) {
        [navController pushViewController:targetViewController animated:YES];
    }

  }