Question

I am trying to update a label on view controller 1 by pressing a button on different view controller 2. I have this IBAction in the view controller 2:

- (IBAction)done:(id)sender {

    DropPinVC * vc = [[DropPinVC alloc]init];

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

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

    vc.TypeLabel.text = updatedLabel;

    [self closeScreen];
}

However, the label on view controller 1 does not update. Does anybody know a solution to this problem?

Was it helpful?

Solution

vc is a new instance of DropPinVC class declared in the scope of the action posted, and is not the same instance as the one you want to update.

One way to achieve this is to keep a pointer to the first view controller.

In order for viewController2(vc2) to update a UILabel that is owned by viewController1(vc1), vc2 needs a reference to vc1 so it can access the label.

Add a property to vc2 of type DropPinVC

@property (nonatomic, strong) DropPinVC *vc1Ref;

Assuming vc1 allocates and initialises vc2 then where after this happens assign the vc1Ref property.

vc2.vc1Ref = self;

Now in the IBAction, your code can now access the correct instance and update the correct label.

- (IBAction)done:(id)sender {

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

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

self.vc1Ref.TypeLabel.text = updatedLabel;

[self closeScreen];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top