Smitha Smitha - 1 year ago 57
iOS Question

MVVM Sample / Example Implementation in iOS

HAs anyone implemented MVVM pattern in your iOS app without using ReactiveCocoa?

Found lots of examples here, but all of them use Reactive Cocoa. I wanted a simple example of MVVM implementation.

Answer Source

Reactive Cocoa is definitely not required for MVVM. I have built a very successful MVVM framework w/o any bindings at all. Bindings are not a requirement for MVVM.

Specifically, the linkage between the View Model and the View does require the View Model to signal to the View that it needs to update its data. This can be achieved using Reactive Cocoa, KVO (I really like Facebook's KVOController), or even using a simple delegate pattern.

The View Model knows when the View needs to update - either data has changed, or you're making an async data request via the Model and the Model has been loaded into the View Model.

When you set up your View, you could bind each control to the corresponding value on the View Model. I have found that when I need to churn out screens, this can get very tedious. Instead, I'd rather have a single method that is called when the View Model signals that the View should update itself. Within that method, I'm simply going to set all of my control properties.

Now, you only need to concern yourself with how that method is triggered. In my personal framework, I leverage KVO and my ViewControllers monitor a timestamp property on my ViewModel baseclass. Any time my view models update their underlying data, its timestamp is updated which triggers the update. You could just as easily have the View Controller register itself as the ViewModel's update delegate and use a standard delegate pattern.

Again, MVVM is not about specific implementation requirements, and more about a higher level concept of separation of concerns, dependency decoupling, and encapsulation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download