Reputation: 41
I read some tutorials about passing data from a ViewController to another using segues.
The common approach it not so good, IMHO: the source ViewController can get a reference to the destination ViewController so that it can set some properties in the destination ViewController. But the fact that the source ViewController knows some piece of the destination ViewController necessarily decreases the decoupling between objects.
I'm wondering if it is possible a more general approach like this one:
Anyone knows if this is possible?
Upvotes: 2
Views: 1269
Reputation: 17898
prepareForSegue:sender:
is the preferred way to pass data from one view controller to another when using storyboards. Watch the Storyboard session from last year's WWDC; you'll see that Apple recommends this method as well.
To reiterate what sobri said, view controller code typically contains the "business logic" of your apps, and therefore is usually the least reusable code in your app. At the time of this writing, I have 7 apps on the app store, and I've never once reused any significant piece of view controller code.
If you want to provide the tiniest bit of abstraction (for example, avoiding a hard dependency on the destination view controller), you could so something like the following. I have nearly this exact code in one of my apps.
- (void) prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
if( [[segue identifier] isEqualToString:@"showLog"] ) {
UIViewController* logView = segue.destinationViewController;
if( [logView respondsToSelector:@selector(setManagedObjectContext:)] ) {
[logView setValue:self.managedObjectContext forKey:@"managedObjectContext"];
}
}
}
You could do something similar with a dictionary, using NSKeyValueCoding
's setValuesForKeysWithDictionary:
. I'd probably just use multiple setValue:forKey:
calls, myself
Upvotes: 1
Reputation: 1685
This is opinion, but I'm of the mind that view controllers do not qualify for object orientation purity.
View controllers are very specific to a single app's architecture, and usually are not intended for general consumption. At least to my mind, there is a distinct difference between generalised classes and classes designed explicitly for the consumption of only one app in one way.
Strongly coupled view controllers make for less complex code. Decoupling of classes is a guideline with the goal of reducing code complexity. If your decoupling results in increased complexity, then it was against the intent of the guideline.
So to answer more directly: I believe the best way to pass data between view controllers is for the sending view controller to know the interface of the receiving view controller, and to hand it the variables directly. Doing otherwise could be considered a premature optimisation.
Upvotes: 0