Passing model objects from one view controller to another in a navigation stack

前端 未结 5 1272
刺人心
刺人心 2021-01-24 04:58

I have two UITableViewControllers. One displays a list of names and on tapping any cell will push the second TableViewController which enables the user to edit the name in a UIT

相关标签:
5条回答
  • 2021-01-24 05:38

    I see mainly three options:

    1. 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;

    2. 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;

    3. 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.

    0 讨论(0)
  • 2021-01-24 05:43

    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.

    0 讨论(0)
  • 2021-01-24 05:45

    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];
       }
    
    0 讨论(0)
  • 2021-01-24 05:54

    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];
    
    0 讨论(0)
  • 2021-01-24 06:00

    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 !

    0 讨论(0)
提交回复
热议问题