Anuradh S Anuradh S - 3 months ago 19
Objective-C Question

Objecitive C - How to send SecondVC label text to FirstVC and update the FirstVC label text

In my case there are two

ViewControllers
. In my first view controller there is a label and when view load, it's text should display as
1
. then there is a button, when it click,navigate to second view controller. In the second view , there is a stepper and label. If user tap
+
,second view's label text change from
1
to
9
,for the
-
also same(decrease the value). in the second view also there is a button.when it click, second view dismiss (from the first view to second I used
presend Modally
kind segue with
over Current Context
presentation.that means when dismiss this secondview, firstview does not load again,it exists in the background). so what I want is to send the second view's label text (after changed by the stepper), as first view's text and update the first view's label.(think if the second view's label text is
3
, first view's label text should update from
1
to
3
). I tried with
NSUserdefaults
.this is my code.

this is my second view controller

- (void)viewDidLoad {
[super viewDidLoad];


//set default value for adult label
NSUInteger defaultAdultVal = self.adultstepper.value;
self.adultcountLabel.text = [NSString stringWithFormat:@"%d", defaultAdultVal];

}




- (IBAction)adultcountAction:(UIStepper *)sender {

NSUInteger adultVal = sender.value;
self.adultcountLabel.text = [NSString stringWithFormat:@"%d", adultVal];

NSString *adultCount = [NSString stringWithFormat:@"%d", adultVal];
[[NSUserDefaults standardUserDefaults] setObject:adultCount forKey:@"adultcount"];
[[NSUserDefaults standardUserDefaults] synchronize];

}
- (IBAction)DoneAction:(id)sender {

[self dismissViewControllerAnimated:YES completion:nil];
}


and this is my second view controller

- (NSString *)testingAsign
{
NSString *adltCount = [[NSUserDefaults standardUserDefaults] objectForKey:@"adultcount"];
return adltCount;
}


I'm getting the value with this method in the first view, and I want to update first view's value but it didn't work.

Answer

this can be done with so many ways like using delegate methods coredata , nsnotifications and nsuserdefaults. from all these , one of the easiest way to pass data backward, we can easily use NSUserDefaults. this is a sample project of passing data backwark using nsuserdefaults. use this github project and give it a try. project url : pass data backward using NSUserDefaults in ios, objective C

Comments