So I have two views A and B. A is a profile view, B is a login view. A loads B in the ViewDidLoad Method using
LoginViewController *lvc = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:[NSBundle mainBundle]]; //make new instance of LoginViewController
[self presentModalViewController:lvc animated:NO]; //present the LoginViewController
[lvc release];
in the login View, if the login is successful, the view is removed
[self dismissModalViewControllerAnimated:YES];
On the login view, It downloads some data which I want to display on the profile view. How would I go about sending the data to the profile view and displaying it in the xib. I believe the profile view is already displayed but is just hidden.
This is a basic “communicate between two classes” question. There are many ways to do this, but here are three. I only wrote sample code for delegation (because I think that’s probably the best choice in your situation), but let me know if you want examples of notifications or KVO.
Delegation Implement a delegation or callback method in Class A. Delegation is best for small class hierarchies. If Class A is the only class that will load B and A is the only class who cares what happens in B, then delegation is the easiest way to move data around. It’s simple to implement, it’s simple to understand and there’s a clear relationship between the classes.
In the login view controller do something like this in the header:
… and this in the implementation:
Notification Class A will register to listen for login notifications. Class B will post login notifications. Notifications are best if the classes that care about login are distributed. i.e. there are many classes that care about a login event and they may not necessarily have a direct relationship with the class that is performing the login.
Key Value Observing KVO is best if you don’t particularly care about the login event, you care about the changes to the data. You will have some class that manages your data, probably an
NSManagedObjectif you are using Core Data. Class A will observe changes to whatever property it’s interested in. YourLoginViewControllerwill update that data class when it is finished downloading data. Class A will be notified that the data has changed.Whatever solution you decide to use, the choice ultimately comes down to asking, “What does Class A care about?”. Does Class A need to know that Class B successfully logged in? Use delegation. Does Class A need to know that somewhere, some class logged in? Use notifications. Does Class A not care about logins, it only needs to know if data has changed? Use KVO.