1

I've been thinking about this and have read through another stackoverflow question regarding the best recommended way to communicate between view controllers. However, the question/answer for that doesn't seem to address the best approach for the reverse behavior.

i.e. to pass data from ParentController to its ModalController, we could initialize ModalController like initWithDataToProcess:.

But what if we want to do the reverse? How would I notify the previous controller about a new data?

e.g. User clicks on 'new person' button on the ParentController. I initiate a new ModalController and present the user with a person editor view via presentModalViewController:. User clicks on 'done' to add a new person. I dismissModalViewController: and UI returns to the ParentController's view.

Using a global field reference in a singleton object (app delegate or other) is bad. delegation (via formal protocol) and notifications (via NSNotificationCenter) seems overkill. Any suggestions?

Community
  • 1
  • 1
  • In .NET land, it's not an issue since a modal call (`ShowDialog()`) is a blocking call. Doesn't seem to be the case with Objective-c/Cocoa with `presentModalViewController:` – JeffreySadeli Oct 15 '10 at 16:06

2 Answers2

1

It is generally cleaner to use notifications. Just add your observer like this....

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappened:) name:@"MyNotification" object:nil];

and elsewhere in your code you'd post the notification whenever you need to.

[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];

In the example I'm passing self but you can pass any object you wish really and it will be fed to your somethingHappened: function

The important thing is to keep the @"MyNotification" very descriptive and unique. Adding your project name to the beginning is a good way to keep things unique...eg. @"ProjAXViewHasGotData"

Amanuel
  • 26
  • 1
0

A delegate is pretty much the minimum you can do. If you think it is too much of a hassle to declare a new protocol for this, just pass in the parent view controller and have the modal one call a method on it.

willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
  • 1
    *HOW* do you "just pass it"... and "have the modal one call it"? ( Why do so many people answer questions with "you do it... just by doing it"... instead of telling *HOW* you do it?) – Patricia Oct 16 '10 at 03:10