Passing model objects from one view controller to another in a navigation stack
I have two UITableViewControllers. One displays a list of names and on ta开发者_如何学Gopping any cell will push the second TableViewController which enables the user to edit the name in a UITextField.
Now I am able to pass the name string from the first TableViewController to the second. (I'm doing this by creating a property in the second TableViewController which I'm setting just before pushing the second TableViewController) But how do I pass the edited name string from the second to the first (so that I can update the first table with the edited name)?
I see mainly three options:
you could define your model as a singleton, which is easily accessible from every other object. In this case think about concurrent access to the model, it any;
have the model private to the first controller, but instead of passing the string to the second controller, pass a pointer to the model, so you can read and write to it;
pass the second controller a pointer to the first, so you can signal it (by calling some specific method); this is ok if you subclass the controller, otherwise you should use a delegate.
A fourth option would be using notifications, but I think that 1 or 2 a the way to go.
Create a mutable array property in the first controller, and pass that array and an index to the second controller.
FirstController.h
@property (nonatomic,retain) NSMutableArray *myStrings;
FirstController.m
@synthesize myStrings;
init {
self.myStrings = [NSMutableArray arrayWithCapacity:8];
}
didSelectRowAtIndexPath {
SecondVC *vc = [[SecondVC new];
[self.theStrings addObject:@"Original String"]; // or replaceAtIndex: indexPath.row
vc.theStrings = self.myStrings;
vc.theIndex = indexPath.row;
//push detail vc.
}
SecondController.h
@property (nonatomic, retain) NSMutableArray *theStrings;
@property (nonatomic ) int theIndex;
SecondController.m
@synthesize theStrings;
@synthesize theIndex;
doneEditingMethod {
[self.theStrings replaceObjectAtIndex: self.theIndex withObject: myNewString];
}
Maybe you should take a look at the delegate pattern which could save you a lot of time ! :-)
You know it's like using an UITableView datasource. With a delegate (or datasource), you can ask or set informations to a root controller.
Maybe it's the best option ! (so google "objective-c delegate")
Good luck !
Are they connected by a navigation controller?
If so, this could solve the problem
// in SecondViewController.m
NSArray* controllers = self.navigationController.viewControllers;
UITableViewController* firstViewController = [controllers objectAtIndex:controllers.count-2];
There are several ways to do this. I, personally, use a third-party class to house strings and just reference that class as I move between UITableViews.
精彩评论