Pass NSString from one class to another
I have 开发者_StackOverflow中文版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
...
FirstViewController *controller = [[FirstViewController alloc]init];
...different from the original instance that (I'm assuming) pushed the SecondViewController
and to which you are returning via popViewControllerAnimated:
.
Basically, what you need is to pass data back to the controller that pushed the SecondViewController
, in this case, the FirstViewController
.
Perhaps, the easiest way to achieve this is what @Ladislav suggested in his comment:
NSArray *viewControllers = [self.navigationController viewControllers];
FirstViewController *firstVC = [viewControllers objectAtIndex:[viewControllers count] - 2];
However, keep in mind that this introduces a direct dependency between SecondViewController
and FirstViewController
. Or, in other words, SecondViewController
is now tightly coupled to FirstViewController
.
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?
精彩评论