ViewModel creation boilerplate in table/collectionviews #25
Description
One problem I've yet to find a solution to using MVVM is where to neatly take care of Model > ViewModel conversion/wrapping.
I tend to have a ViewModel class per each TableViewCell/CollectionViewCell, and hence when I create a datasource that initializes itself with a set of Model objects, I need to do something like the following:
+ (NSArray *)viewModelsFromModels:(NSArray *)models {
NSMutableArray *array = [NSMutableArray array];
for (Model *model in models) {
ViewModel *viewModel = [[ViewModel alloc] initWithModel:model];
[array addObject:viewModel];
}
return array;
}
This is....kind of gross, and also leads to creeping complexity and difficulty of use whenever you have to unwrap viewmodels to get to their underlying models (eg, when handing off a viewmodel to another class that wants to create it's own viewmodel).
I've thought of a few solutions to this but none really work:
- Create categories on the underlying model that creates a viewmodel for whatever our current context is. This a: gets messy and b: doesn't let us do any caching/lazy computation of viewmodel properties (which is a nice bonus), it also could have performance hits since we'd be creating/destroying these objects frequently.
- Have every cell store a viewModel and have the datasource update the underlying
model
property of the viewModel. This also means we don't get any nice caching of our viewModel properties, and limits us to functions that expose/transform the underlying models properties in realtime as they are called. - Tucking away this code into a generic macro like
MVVM_ADAPT(collection, targetClass)
. This is sort of okay.
I still haven't come up with a nice way around this, it's my only gripe with MVVM right now. What do you do in your projects?