Assume I have abstract base model class called MoneySource. And two realizations BankCard and CellularAccount. In MoneysSourceListViewController I want to display a list of them, but with ListItemView different for each MoneySource subclass.
What if I define a category on MoneySource
@interface MoneySource (ListItemView)
- (Class)listItemViewClass;
@end
And then override it for each concrete sublcass of MoneySource, returning suitable view class.
@implementation CellularAccount (ListItemView)
- (Class)listItemViewClass
{
return [BankCardListView class];
}
@end
@implementation BankCard (ListItemView)
- (Class)listItemViewClass
{
return [CellularAccountListView class];
}
@end
@implementation MoneySourceListController
- (ListItemView *)listItemViewForMoneySourceAtIndex:(int)index
{
MoneySource *moneySource = [items objectAtIndex:index];
Class viewClass = [moneySource listItemViewClass];
ListItemView *view = [[viewClass alloc] init];
[view setupWithMoneySource:moneySource];
return [view autoreleased];
}
@end
so I can ask model object about its view, not violating MVC principles, and avoiding class introspection or if constructions.
Thank you!
If your current structure is MoneySource as your Model and CellularAccount | BankCard as your Controllers because they've extended the Model via categories, then I think you still have a categorically bad design that does not follow MVC. The extension leaves the Controller with functionality from the Model that it should not have.
– Sep 18 '12 at 16:12