不使用NSUserDefaults从不同的View Controller更新标签

时间:2014-03-09 01:58:17

标签: ios uiviewcontroller label nsuserdefaults updating

我试图通过按下不同视图控制器2(TypeLocation)上的按钮来更新视图控制器(DropPinVC)上的标签。

在DropPinVC.m中我有:

- (void)viewDidLoad
{
    TypeLocation *VC2 = [[TypeLocation alloc] initWithNibName:@"TypeLocation" bundle:nil];
    VC2.myVC2 = self;
    [super viewDidLoad];
}

在TypeLocation.h中我有:

@property (nonatomic, strong) DropPinVC *myVC2;

在TypeLocation.m中,我有:

-(IBAction) switchValueChanged
{

    if (self.TASwitch.on){
    TypeLocation = @"Tourist Attraction";
    [[NSUserDefaults standardUserDefaults] setObject:TypeLocation forKey:@"Type Location"];
}
else {
    TypeLocation = @"Unsafe Location";
    [[NSUserDefaults standardUserDefaults] setObject:TypeLocation forKey:@"Type Location"];

    DropPinVC *myVC2 = [[DropPinVC alloc] initWithNibName:@"DropPinVC" bundle:nil];

    NSString *updatedLabel = [[NSUserDefaults standardUserDefaults] stringForKey:@"Type Location"];

    NSLog(@"Updated Label = %@", updatedLabel);

    myVC2.TypeLabel.text = updatedLabel;

    [self closeScreen];

}

但是,视图控制器1上的标签不会更新。有人知道这个问题的解决方案吗?谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您需要将字符串updateLabel传递给您在DropPinVC中创建的字符串属性,并让该控制器在viewDidLoad中填充其标签。您的方法不起作用,因为在您尝试设置标签文本时尚未加载视图,因此myVC2.TypeLabel将为nil。

另外,你没有在TypeLocation中使用你的属性myVC2。这一行,

DropPinVC *myVC2 = [[DropPinVC alloc] initWithNibName:@"DropPinVC" bundle:nil];

应该是,

self.myVC2 = [[DropPinVC alloc] initWithNibName:@"DropPinVC" bundle:nil];