Unit 2: MVVM Architecture

INT372 — Iphone Application Programming 10 min read

I. Architectural Orientation

iPhone application programming uses Apple’s iOS SDK, Xcode, Swift, and interface frameworks such as UIKit or SwiftUI. In this unit, UIKit-based development is organized through Model–View–ViewModel (MVVM), an architectural pattern that separates application data, user-interface presentation, and presentation logic.

  • Model: Represents domain data and business rules, such as a User, Product, or network response.
  • View: Displays information and receives user interaction; in UIKit, views commonly come from UIView, UILabel, UIButton, and related classes.
  • ViewModel: Converts model data into values and commands required by the view without directly controlling visual components.
  • View controller: Coordinates UIKit views and lifecycle events; in MVVM, it should remain relatively thin and delegate presentation logic to a view model.
  • Xcode: Provides source editing, interface design, compilation, debugging, simulation, testing, and project management.
  • Event-driven operation: iOS applications respond to events such as launches, button taps, notifications, interruptions, and scene-state changes.

II. MVVM Architecture — Separation of Presentation Responsibilities

A. Introduction to MVVM architecture

MVVM divides an application into collaborating layers so that interface code is easier to maintain, test, and extend.

  • Model responsibility: Stores data and implements domain behaviour independently of the interface.
    • A model may be a Swift structure such as struct Student.
    • It may obtain data from files, databases, sensors, or web services.
  • View responsibility: Presents view-model output and forwards user events.
    • A storyboard scene and its labels, text fields, and buttons form part of the view.
    • The view should not contain database or networking logic.
  • ViewModel responsibility: Holds presentation state and transforms model values into display-ready information.
    • It may convert 78.5 into "78.5%".
    • It should normally avoid direct references to UILabel or UIButton.
  • Communication flow: Data generally moves from the model through the view model to the view, while user input travels from the view toward the view model.
SWIFT
struct Student {
    let name: String
    let score: Double
}

final class StudentViewModel {
    private let student: Student

    init(student: Student) {
        self.student = student
    }

    var displayText: String {
        "\(student.name): \(student.score)%"
    }
}
  • Concrete roles: Student is the model, StudentViewModel prepares presentation text, and a label can display displayText.
  • Binding approaches: UIKit projects may update views through closures, delegates, notifications, Combine publishers, or observable properties.
  • Benefits: MVVM improves testability, reduces massive view controllers, promotes reuse, and permits interface changes without rewriting business logic.
  • Limitation: Excessive view-model abstraction can complicate a small application; responsibilities must therefore be assigned deliberately.

III. Xcode Development Environment — Project and Tool Management

A. Introduction to Xcode

Xcode is Apple’s integrated development environment for building, running, testing, and distributing iOS applications.

  • Development tools: It combines a Swift editor, compiler, debugger, Interface Builder, asset management, testing tools, and documentation.
  • Project organization: An .xcodeproj contains build settings, file references, targets, and schemes rather than all source-file contents.
  • Target: Defines one build product, such as an iPhone application or unit-test bundle.
  • Scheme: Selects the target, build configuration, executable, and actions such as Run, Test, Profile, and Archive.
  • Toolbar controls: The Run button builds and launches the selected scheme; the Stop button terminates it.
  • Build feedback: Compiler errors and warnings appear in the Issue navigator and beside relevant source lines.

B. Workspace window

The workspace window is Xcode’s main working area, arranging project resources, editors, controls, and diagnostic information.

  • Toolbar: Contains Run/Stop controls, scheme and destination selectors, activity status, and editor controls.
  • Navigator area: Appears on the left and provides project files, search results, issues, tests, breakpoints, and reports.
  • Editor area: Occupies the centre and displays Swift files, storyboards, property lists, and build settings.
  • Inspector area: Appears on the right and edits attributes, size constraints, connections, and file information.
  • Debug area: Opens below the editor to show variables, stack frames, debugger controls, and console output.
  • Flexible layout: Panels can be shown or hidden to provide more room for code or visual interface work.

C. Working with navigator pane

The navigator pane provides specialized views for locating files and examining development information.

  • Project navigator: Displays groups, Swift files, storyboards, assets, frameworks, and configuration files.
  • Source Control navigator: Shows repository branches, changes, commits, and conflicts when source control is configured.
  • Find navigator: Searches text across files; searching for viewDidLoad locates every matching implementation.
  • Issue navigator: Lists compiler errors, warnings, and analysis findings.
  • Test navigator: Organizes unit and UI tests and records their latest results.
  • Debug navigator: Displays threads, CPU usage, memory information, and active stack frames while debugging.
  • Breakpoint and Report navigators: Manage breakpoints and retain logs of builds, tests, and archives.

D. Utility pane

The utility pane, commonly called the inspector area, displays settings and contextual information for the selected item.

  • File inspector: Shows a file’s name, location, target membership, localization, and interface-document settings.
  • Quick Help inspector: Provides concise documentation for a selected API symbol.
  • Identity inspector: Assigns the custom class, module, restoration identifier, or storyboard identifier.
  • Attributes inspector: Configures visual and behavioural properties of selected controls.
  • Size inspector: Edits position, dimensions, Auto Layout constraints, and content-hugging or compression priorities.
  • Connections inspector: Displays connected outlets, actions, and segue relationships.

IV. Interface Construction — Creating and Designing the Application

A. Interface Builder

Interface Builder is Xcode’s visual editor for constructing UIKit interfaces in storyboards or XIB files.

  • Storyboard: Contains one or more scenes and visual transitions called segues.
  • Scene: Usually represents a view controller together with its root view and child controls.
  • Object library: Supplies components such as labels, buttons, image views, table views, and navigation controllers.
  • Drag-and-drop design: Controls are placed on the canvas and configured without manually creating every object in code.
  • Document outline: Shows the hierarchy of controllers, views, constraints, and layout guides.
  • Runtime loading: The storyboard is compiled into resources from which UIKit instantiates configured objects.

B. Attribute inspector

The Attribute inspector changes the properties of the object currently selected in Interface Builder.

  • Control attributes: A button can receive a title such as "Submit", while a label can receive text, alignment, colour, and line-count settings.
  • View attributes: Background colour, alpha, visibility, tint, interaction, and content mode can be configured.
  • Controller attributes: A view controller can be marked as the initial controller or given presentation settings.
  • Design-time effect: Many changes appear immediately on the canvas.
  • Runtime equivalence: Setting a label’s text in the inspector corresponds conceptually to code such as:
SWIFT
titleLabel.text = "Welcome"
titleLabel.textAlignment = .center
  • Caution: Inspector values provide initial configuration; application code may replace them while the program runs.

C. Simulator and creating project

An iOS project supplies the application structure, while Simulator provides a software-based environment for running it on a Mac.

  • Project creation: Choose an iOS App template, then specify the product name, team, organization identifier, interface, language, and testing options.
  • Bundle identifier: Usually combines the organization identifier and product name, for example com.example.StudentApp.
  • Initial files: A UIKit project commonly includes an application delegate, view controller, assets, configuration resources, and possibly scene-management files.
  • Run destination: Select a simulated device, such as a particular iPhone model and iOS version, before pressing Run.
  • Simulator capabilities: It supports rotation, location simulation, screenshots, memory warnings, and several device configurations.
  • Physical-device difference: Camera behaviour, sensors, performance, battery use, and some services must be verified on actual hardware.

D. Designing UI

UI design arranges controls into an accessible, adaptable, and visually consistent interface.

  • View hierarchy: Place related controls in container views or stack views to establish clear structure.
  • Auto Layout: Express relationships using constraints rather than fixed screen coordinates.
    • A button may be constrained 20 points from the leading and trailing safe-area edges.
    • Its vertical position can be defined relative to a text field.
  • Safe area: Keeps important content away from the status bar, home indicator, and other obstructed regions.
  • Adaptability: Layouts should support multiple iPhone sizes, orientation changes, and larger Dynamic Type text.
  • Accessibility: Controls need meaningful labels, sufficient contrast, usable touch targets, and logical VoiceOver order.
  • Consistency: Standard UIKit controls and familiar navigation patterns reduce user effort.

V. View Controller Interaction — Connecting Interface and Code

A. Looking at view controller

A view controller manages a screen’s view hierarchy and responds to view-related lifecycle events.

  • Class foundation: A UIKit screen commonly subclasses UIViewController.
  • View loading: viewDidLoad() runs after the controller’s view hierarchy has been loaded into memory.
  • Configuration role: Initial text, delegates, view-model bindings, and one-time setup are commonly established there.
  • Navigation role: Controllers may present another controller, perform a segue, or participate in navigation and tab-bar structures.
  • MVVM boundary: The controller connects UIKit objects to the view model but should avoid owning core business rules.

B. Understanding outlets

An outlet is a reference that allows Swift code to access an object created in Interface Builder.

  • Declaration: @IBOutlet marks a property that Interface Builder can connect to a storyboard object.
SWIFT
@IBOutlet private weak var nameLabel: UILabel!
  • Type: UILabel ensures that nameLabel exposes label properties such as text and textColor.
  • Weak reference: weak helps avoid unnecessary ownership because the view hierarchy normally retains the label.
  • Implicitly unwrapped optional: The ! reflects that the connection is assigned after controller initialization but before normal view use.
  • Connection process: Control-drag from the storyboard object to the view-controller code and select Outlet.
  • Failure condition: A broken or missing connection can cause a runtime crash when the property is accessed.

C. Actions

An action connects a user-generated control event to a method in the view controller.

  • Declaration: @IBAction exposes a method to Interface Builder.
SWIFT
@IBAction private func saveTapped(_ sender: UIButton) {
    statusLabel.text = "Saved"
}
  • Sender parameter: sender identifies the control that triggered the method.
  • Control event: A button generally uses the touchUpInside event, indicating a completed tap within its bounds.
  • Outlet–action contrast:
    1. Outlet: Provides a continuing reference from code to an interface object.
    2. Action: Invokes code when a configured interface event occurs.
  • MVVM use: An action should call a view-model operation, then update or bind the interface to the resulting state.

VI. Application Coordination — Delegation and Runtime States

A. Application delegate

The application delegate receives application-level events and participates in process-wide configuration.

  • Class role: A class marked with @main launches the app and conforms to UIApplicationDelegate.
  • Launch configuration: application(_:didFinishLaunchingWithOptions:) performs initialization such as service setup.
  • Shared responsibilities: Notifications, background activity, application shortcuts, and global services may involve delegate methods.
  • Scene-based applications: On modern iOS, visible interface sessions are commonly managed by UISceneDelegate, while the application delegate manages process-level concerns.
  • Architectural caution: The delegate should not become a storage location for unrelated data or screen-specific business logic.

B. Activity life cycle

The application lifecycle describes how an iOS app moves between execution states as the user and system interact with it.

  • Not running: The process has not started or has been terminated.
  • Inactive: The app is in the foreground but temporarily not receiving normal events, such as during an interruption.
  • Active: The interface is visible and receives user interaction.
  • Background: The interface is not visible, although limited code may continue executing.
  • Suspended: The process remains in memory but executes no application code.
  • Typical transition: Launch moves the app toward active; pressing the Home gesture moves it through inactive to background and possibly suspension.
  • Scene callbacks: Methods such as sceneDidBecomeActive(_:), sceneWillResignActive(_:), and sceneDidEnterBackground(_:) report state changes.
  • State preservation: Important data should be saved when it changes or when backgrounding occurs because suspended apps may later be terminated without further execution.