views:

70

answers:

2

How do i send information between two views (and hence, two classes)? Am I looking for my app delegate? Is there a better or alternative way?

A: 

I would use the Application Delegate. Or, if one view owns the other, you can initialize them together and keep the main reference to it in the class.

I always find it useful to have a global Context object to keep global information among views. This information could be, configuration information, device current orientation, database handlers, etc.

For the variables you need cross-access for, you can use Properties.

class VC1 : UIViewController {
   NSString* v1;
   NSString* v2;
}

@property (copy) NSString *v1;
@property (copy) NSString *v2;

And then, in the other view:

class VC2 : UIViewController {
    VC1 *vc1;
}

And in you message implementations in VC2 you can use VC1's v1 and v2 like this:

- (void) someMessage {
   NSLog(@"VC1's v1 value is %@ and v2 value is %@", [vc1 v1], [vc1 v2]);
}

Hope it helps.

Pablo Santa Cruz
Where are my variables and how does one view know about variables in the other?
Moshe
Updated my answer with some code. Hope it helps.
Pablo Santa Cruz
Looks good, but how do I get VC1's value in VC2? Will each View Controller see the other one through the delegate now?
Moshe
+1  A: 

If you want to send information back, you can use target-action (the way UIControl does), or you can send NSNotifications, or use a generic delegate protocol. Unless this is information of use throughout your application, putting it into your app delegate may be overkill.

Ben Gottlieb
I would say that while this is a quick and dirty way to pass data between views, its not good practice. It couples the view controllers together and makes the app hard to maintain and scale.
TechZen
It very explicitly does not couple anything together. Where is the coupling?
Ben Gottlieb
+1 for NSNotifications and delegates
Anurag