Building a Virtual Machine App on MacOS: Part 2

23-03-2025

Last time, I set up a basic user interface where users could view and manage virtual machines. This week, I started learning about the MVVM (Model-View-ViewModel) pattern. I began by reading blog posts and following tutorials to understand its structure and benefits. Once I grasped the core concepts, I started refactoring my virtual machine app to use MVVM.

This transition was much harder than I expected. I struggled to ensure that all views had access to the same data and faced challenges in getting the Settings view to work correctly within the ViewModel.

To solve the data-sharing issue across views, I discovered @EnvironmentObject in SwiftUI. This allows an object to be shared across the environment, making it accessible to multiple views. By passing the ViewModel from the main view, I was able to retrieve data in all other views effortlessly.

Fixing the Settings view was trickier because it included several input options. After researching and using AI assistance, I learned about computed properties and observers. Implementing these within the ViewModel and updating the Settings view accordingly solved the issue.

Refactoring to MVVM also fixed two bugs from last week:

  1. When switching between virtual machines, the settings view previously displayed the old virtual machine's settings. Now, it updates correctly.
  2. When renaming a virtual machine, the title in the list didn't update immediately. This issue was resolved with MVVM.

I also added a feature to create new virtual machines, and thanks to MVVM, implementing this was straightforward.

Overall, this time was all about learning and applying MVVM, which not only improved the structure of my app but also helped resolve existing bugs. Next time, I’ll explore data persistence and work on implementing CRUD operations for virtual machines.