tags:

views:

1483

answers:

5

I'm starting out in iPhone development, and I'm trying to do a Contacts-style controller to add items to a table. I've got the two controllers designed, but I can't seem to figure out how to pass data between them. How can I get data from the modal controller to its parent?

Just trying to call methods on parentViewController won't work (and results in compiler warnings and crashes). I've considered moving the data out of the controller itself (which is going to happen anyway, I'm just trying to keep things as simple as possible for now), but even then I still have to somehow tell the parent view to refresh its data. Again, how can I do this?

+1  A: 

You either keep a link to the sub view you create and ask it for data that has changed on return, or else ad yourself as a delegate of a subview and have it call you back directly (which does work if you have a valid reference).

Kendall Helmstetter Gelner
How does the parent view know when the modal view was dismissed?
Stephen Touset
When the parent has "viewWillAppear" called. One pattern is to keep a reference to the modal view controller in the parent, and see if that is set in viewWillAppear to handle the case of that model view returning - then you set the reference to nil so that coming back into the screen by other means does not trigger that logic.
Kendall Helmstetter Gelner
A: 

In short, use delegate.

I would suggest you have a look at Lecture 11: Text input, Presenting content modally (May 6) - iPhone App Programming course offered by Stanford. Search for it on iTunes U.

Download this sample app if you want to know how to implement delegate: http://www.stanford.edu/class/cs193p/downloads/11-Pickers.zip

QAD
+2  A: 

I've considered moving the data out of the controller itself (which is going to happen anyway

I think now may be the time to follow that consideration and create a separate "ContactList" model object to store your data.

Your modal view controller just adds new "Contacts" into the "ContactList".

Your TableViewController should observe the same "ContactList". As items are added/removed to/from the "ContactList" your TableViewController will simply add and remove rows from its tableView.

In this way you will keep each ViewController independent, your code will be more flexible and adding/removing single rows will be much more efficient than reloading an entire tableView.

Jonathan Arbogast
A: 

Hello Do you have a sample app from lectures 11, because this page not found. Me mail is [email protected] Thanks

ovidiu
A: 

I had the same question and found this sample code: http://developer.apple.com/iphone/library/samplecode/LocateMe/Introduction/Intro.html

Helped me a ton and was pretty easy to figure out from the code.

Gorgando