I have some weird issue here as somehow I am unable to pass NSString from one class to another. I deployed the same method that worked on other classes.
I am trying to pass a string from secondViewController to my firstViewController. Here’s what I did.
firstViewController.h
NSString *pickUpAddressString;
@property (nonatomic, retain) NSString *pickUpAddressString;
firstViewController.m
@synthesize pickUpAddressString;
-(void) viewWillAppear:(BOOL)animated {
NSLog(@"pickUpAddressString is %@", pickUpAddressString); // why it's null here?
PickUpAddress.text = pickUpAddressString; // PickUpAddress is a UITextField
}
secondViewController.m
FirstViewController *controller = [[FirstViewController alloc]init];
controller.pickUpAddressString = selectedAddress; // here, I set the string
NSLog(@"selected address :%@\npickUpAddressString:%@", selectedAddress, controller.pickUpAddressString); // I had verified that both strings are valid.
[self.navigationController popViewControllerAnimated:YES]; // pop to firstView
You are creating a new instance of
FirstViewController……different from the original instance that (I’m assuming) pushed the
SecondViewControllerand to which you are returning viapopViewControllerAnimated:.Basically, what you need is to pass data back to the controller that pushed the
SecondViewController, in this case, theFirstViewController.Perhaps, the easiest way to achieve this is what @Ladislav suggested in his comment:
However, keep in mind that this introduces a direct dependency between
SecondViewControllerandFirstViewController. Or, in other words,SecondViewControlleris now tightly coupled toFirstViewController.In a nutshell, when it comes to pass data back up the hierarchy, it is a best practice to use loose coupling to avoid direct dependencies between your view controllers (tight coupling). The benefits of doing so include code reusability and testability. In order to achieve loose coupling you need to define a generic interface for observers (e.g. delegation, notifications, etc).
It is also worth mentioning the importance of putting state information in model objects. Avoid putting data inside the controllers, unless it’s strictly presentation data.
More on this topic: What's the best way to communicate between view controllers?