我将字符串从一个视图控制器传递到另一个视图控制器时获得null值

时间:2017-04-19 18:39:12

标签: objective-c string isnull

FirstView控制器。

usernameTextField.text = [user objectForKey:@"name"];
strValue =[NSString stringWithFormat:@"%@", self.usernameTextField.text];

if ([strValue isEqualToString:@""])
{
    NSLog(@"myString IS empty!");
    self.usernameTextField.text = @"";

}
else
{
    NSLog(@"FIRSTPAGE IS NOT empty, it is: %@", strValue);
    HomeViewController *homeVC = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];
    UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:homeVC];
    [homeVC setStr1:strValue];

    [self.navigationController pushViewController:homeVC animated:YES];

}

第二个视图控制器

[super viewDidLoad];

defaults = [NSUserDefaults standardUserDefaults];

NSLog(@"Fetched STRING IS  %@!",strValue);

strValue =[NSString stringWithFormat:@"%@", self.usernameLabel.text];

NSLog(@" STRING IS  %@!",strValue);


if ([strValue isEqualToString:@""])
{
    NSLog(@"myString IS empty!");

}
else
{
    NSLog(@"Home string IS NOT empty, it is: %@", strValue);


}
usernameLabel.text =[NSString stringWithFormat:@"Hi %@ !", strValue];

我将firstVC的strValue传递给SecondVC。我在firstVC中获得了我的价值,但是在传递!!时,我获得了零的秒值

NSLog(@“获取STRING IS%@!”,strValue); 在这里,我得到NULL值。

建议我,我的错误是什么!

1 个答案:

答案 0 :(得分:0)

尝试在之前调用[homeVC setStr1] ,然后启动UINavigationController。像这样:

HomeViewController *homeVC = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];
[homeVC setStr1:strValue];
UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:homeVC];

[self.navigationController pushViewController:homeVC animated:YES];

初始化导航控制器时,它会在其根视图控制器上调用-loadView(后者会触发对-viewDidLoad的调用)。在您的代码中,这是在您设置字符串属性之前发生的,因此在调用-viewDidLoad时字符串为nil。首先设置属性将阻止这种情况发生。