Guferos
Guferos

Reputation: 4367

Passing data back between View Controllers embed in UINavigationController

I have view controller embed in navigation controller with one property (nonatomic strong NSMutableArray *myData), when I am pushing second view I am also passing my array data to this view using this method:

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {  
      if ([[segue identifier] isEqualToString:@"secondView"]) {
          SecondViewController *svc = [segue destinationViewController];
          svc.myDataInSecondView = self.myData;
     }

My question is: Why if I change any values in my myDataInSecondView array and than I will come back to first view my values in myData array are changed as well? I always thought that I have to use custom protocols and delegates to pass any data back to the previous view.

Upvotes: 0

Views: 1874

Answers (1)

nevan king
nevan king

Reputation: 113757

The way you're doing it is a very common way of sharing data between view controllers. The second view controller has a property that can be set by the first view controller. The property is a pointer, the same as in the first view controller. Both point at the same place in memory, so either view controller can change that same data.

If you don't want the second view controller to alter the data, set the property as copy.

@property (nonatomic, copy) MyData *myData;

Upvotes: 1

Related Questions