iosviewcontrollerivar

IOS Data Between View Controllers


I have a navigation controller with 2 view controllers, A and B.

A and B both have a property

@property (strong, nonatomic) NSString *string;

string is created in controller A and passed to controller B

ViewControllerB.string = self.string;
[self.navigationController pushViewController:ViewControllerB];

In View Controller B, string is modified and when I pop to View Controller A, the value of string has not changed.

Since they both hold a strong reference to it, shouldn't string be changed in both View Controllers?

Am I missing something?


Solution

  • In View Controller B, string is modified

    This is impossible since you're using NSString, not NSMutableString. If you replace it within ViewControllerB:

    self.string = @"some other string";
    

    Then you are setting ViewControllerB's string property to reference that new string, but other references to the original string are not affected.

    If you really want both view controllers to modify the same string, use NSMutableString. But shared mutable state is probably bad. Instead, consider using an intermediary class (like a data source), or the delegate pattern for ViewControllerB to hand ViewControllerA an updated string.