25
Let's say we have the following classes:
View
@interface ArticleView : UIView
@property IBOutlet UILabel *titleLabel;
@property IBOutlet UILabel *bodyLabel;
@end
Model
@interface Article : NSObject
@property NSString *title;
@property NSString *body;
@end
Controller
@interface ArticleViewController : UIViewController
@property Article *myArticle;
@property ArticleView *myArticleView;
- (void)displayArticle;
@end
@implementation
- (void)displayArticle {
// OPTION 1
myArticleView.titleLabel.text = myArticle.title;
myArticleView.bodyLabel.text = myArticle.body;
// ... or ...
// OPTION 2
myArticleView.article = myArticle;
}
@end
OPTION 1
- PRO: Both the view and model aren't coupled to each other.
- CON: The controller needs to know the details of both the model and view.
OPTION 2
- PRO: The controller code is light and flexible (if the view or model change, the controller code stays the same.
- CON: The view and model are coupled and therefore less reusable.
In OPTION 2, ArticleView will have to be changed to hold a reference to the model:
@interface ArticleView : UIView
@property IBOutlet UILabel *titleLabel;
@property IBOutlet UILabel *bodyLabel;
@property Article *article;
@end
The article setter can then be overwritten to update the view accordingly, like so:
- (void)setArticle:(Article *)newArticle {
_article = newArticle;
self.titleLabel.text = _article.title;
self.bodyLabel.text = _article.body;
}
So my question is, which one of these two options is best in terms of OO and iOS/MVC best practices?
I've certainly seen