<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by SamHastings on Medium]]></title>
        <description><![CDATA[Stories by SamHastings on Medium]]></description>
        <link>https://medium.com/@samhastingsis?source=rss-e84c9b3dd4e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aHc43kqA2GPCOOcef1jXhg.jpeg</url>
            <title>Stories by SamHastings on Medium</title>
            <link>https://medium.com/@samhastingsis?source=rss-e84c9b3dd4e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:22:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samhastingsis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MVC vs MVVM — iOS implementations: it’s about who knows whom.]]></title>
            <link>https://medium.com/@samhastingsis/mvc-vs-mvvm-ios-implementations-its-about-who-knows-whom-29a114c6513a?source=rss-e84c9b3dd4e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/29a114c6513a</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[SamHastings]]></dc:creator>
            <pubDate>Fri, 08 May 2026 16:08:38 GMT</pubDate>
            <atom:updated>2026-05-21T14:22:18.837Z</atom:updated>
            <content:encoded><![CDATA[<p>See the accompanying <a href="https://github.com/SamHastings1066/MVC_and_MVVM">Github repo</a> for the demo app accompanying this article.</p><h3>Architecture diagrams</h3><p>There are a lot of MVC/MVVM architecture diagrams out there; it’s a bit of a mess. Below is my best effort to present two representations from definitive sources.</p><p>In its <a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html">Documentation Archive</a>, Apple, who <a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html#:~:text=MVC%20is%20central%20to%20a%20good%20design%20for%20a%20Cocoa%20application">used to endorse MVC for Cocoa applications</a>, represents the Model-View-Controller design pattern with the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrssEynV3tVdH7fpyzcArQ.png" /><figcaption><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html">Apple’s MVC diagram</a></figcaption></figure><p>Microsoft, <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel#:~:text=It%20was%20invented%20by%20Microsoft%20architects%20Ken%20Cooper%20and%20Ted%20Peters">who’s engineers invented MVVM</a>, represent the pattern with this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fv7yrZZAuEo3xK_UE-xk6Q.png" /><figcaption><a href="https://learn.microsoft.com/en-us/dotnet/architecture/maui/mvvm?utm_source=chatgpt.com#:~:text=of%20an%20app.-,The%20MVVM%20pattern,-There%20are%20three">Microsoft’s MVVM diagram</a></figcaption></figure><p>Below are two alternative implementations of the same screen of an iOS app — one MVC (using UIKit) and one MVVM (using SwiftUI). The purpose of the screen is to display whether a document has been signed, and allow a user to sign or unsign the document. For both architectures, every arrow in the corresponding diagram is mapped to its implementation in the code.</p><p><strong>The Model</strong> is pure Swift and is the same for both architectures. It consists of two components — Document and DocumentController, but don’t worry about them too much for now:</p><pre>//  Document.swift<br><br>struct Document {<br>    var isSigned: Bool<br>}</pre><pre>//  DocumentController.swift<br><br>final class DocumentController {<br>    private(set) var document: Document<br>    var observerMVC: ((Bool) -&gt; Void)?<br>    var observerMVVM: ((Bool) -&gt; Void)?<br>    init(document: Document) { self.document = document }<br>    var isSigned: Bool {<br>        get { document.isSigned }<br>        set {<br>            guard newValue != document.isSigned else { return }<br>            document.isSigned = newValue<br>            notify()<br>        }<br>    }<br>    func toggle() { isSigned.toggle() }<br>    private func notify() {<br>        observerMVC?(document.isSigned)<br>        observerMVVM?(document.isSigned)<br>    }<br>}</pre><h3>MVC</h3><p><strong>The Controller:</strong></p><pre>//  ViewController.swift<br><br>import UIKit<br><br>final class ViewController: UIViewController {<br>    private let viewMVC = ViewMVC()<br>    private let documentController: DocumentController<br><br>    init(documentController: DocumentController) {<br>        self.documentController = documentController<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        documentController.observerMVC = { [weak self] _ in<br>            self?.updateView()<br>        }<br><br>        setUpView()<br>        updateView()<br>    }<br><br>    private func setUpView() {<br>        view.addSubview(viewMVC)<br>        viewMVC.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint.activate([<br>            viewMVC.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            viewMVC.centerYAnchor.constraint(equalTo: view.centerYAnchor),<br>        ])<br>        viewMVC.onTap = { [weak self] in<br>            self?.documentController.toggle()<br>        }<br>    }<br><br>    private func updateView() {<br>        viewMVC.updateAppearance(isSigned: documentController.isSigned)<br>    }<br>}</pre><p><strong>The View:</strong></p><pre>//  ViewMVC.swift<br><br>import UIKit<br><br>class ViewMVC: UIButton {<br>    let signedTitle = &quot;☑︎ Signed&quot;<br>    let unsignedTitle = &quot;☐ Unsigned&quot;<br><br>    var onTap: (() -&gt; Void)?<br><br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        addTarget(self, action: #selector(handleTap), for: .touchUpInside)<br>    }<br><br>    required init?(coder: NSCoder) {<br>        super.init(coder: coder)<br>        addTarget(self, action: #selector(handleTap), for: .touchUpInside)<br>    }<br><br>    func updateAppearance(isSigned: Bool) {<br>        let title = isSigned ? signedTitle : unsignedTitle<br>        setTitle(title, for: .normal)<br>        setTitleColor(.systemBlue, for: .normal)<br>    }<br><br>    @objc private func handleTap() {<br>        onTap?()<br>    }<br>}</pre><p>Now to map each MVC diagram arrow to the code…</p><p><strong>View — <em>user action</em> → Controller</strong></p><p>In MVC the View needs to communicate user actions (e.g. screen taps) to the Controller <strong>without knowing about the Controller</strong>. We achieve this with <strong>callback binding</strong> — it’s just one possible approach, but suitable for a simple use case like this. The View defines an onTap callback:</p><pre>//  ViewMVC.swift<br>var onTap: (() -&gt; Void)?</pre><p>which is set in the Controller, thereby binding the Controller to the View — by allowing the View to call code in the Controller without knowing about the Controller:</p><pre>//  ViewController.swift<br><br>viewMVC.onTap = { [weak self] in<br>            self?.documentController.toggle()<br>        }</pre><p>via UIKit’s addTargetmethod — an implementation of the <a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/Devpedia-CocoaApp/TargetAction.html">target-action pattern</a>— when a user physically taps the View it sends itself a message to call the onTap callback:</p><pre>//  ViewMVC.swift<br><br>override init(frame: CGRect) {<br>        ...<br>        addTarget(self, action: #selector(handleTap), for: .touchUpInside)<br>    }<br><br>...<br><br>@objc private func handleTap() {<br>        onTap?()<br>    }</pre><p><strong>Controller — <em>update </em>→ View</strong></p><p>The Controller must update the View to reflect changes in the Model. <strong>In MVC the Controller holds a direct reference to the View</strong>:</p><pre>//  ViewController.swift<br><br>private let viewMVC = ViewMVC()</pre><p>The Controller is then free to call the View’s public method updateAppearance, passing it the Model’s isSigned state. In this way the Controller binds the Model to the View — by allowing the View to access the Model’s state without knowing about the Model:</p><pre>//  ViewController.swift<br><br>private func updateView() {<br>        viewMVC.updateAppearance(isSigned: documentController.isSigned)<br>    }</pre><p><strong>Model — <em>notify</em>→ Controller</strong></p><p>The Model is responsible for notifying the Controller of changes to its state —<strong> but the Model should not know about the Controller</strong>. Once again, this is achieved using callback binding. The Model defines an observerMVC callback:</p><pre>//  DocumentController.swift<br><br>var observerMVC: ((Bool) -&gt; Void)?</pre><p>which is set in the Controller, thereby binding the Controller to the Model — by allowing the Model to call code in the Controller without knowing about the Controller.</p><pre>//  ViewController.swift<br><br>documentController.observerMVC = { [weak self] _ in<br>            self?.updateView()<br>        }</pre><p>The observerMVC callback is then called whenever theDocumentController’s isSigned state changes (i.e. whenever the document is signed or unsigned):</p><pre>//  DocumentController.swift<br><br>var isSigned: Bool {<br>        ...<br>        set {<br>            ...<br>            notify()<br>        }<br>    }<br><br>private func notify() {<br>        observerMVC?(document.isSigned)<br>        ...<br>    }</pre><p><strong>Controller — <em>update </em>→ Model</strong></p><p>The Controller must update the Model to reflect user actions, which is simple because the Controller holds a direct reference to the Model:</p><pre>//  ViewController.swift<br><br>private let documentController: DocumentController</pre><p>The Controller then binds the Model’s public method toggleto the View by capturing that method inside the closure it assigns to the View’s onTapcallback:</p><pre>//  ViewController.swift<br><br>viewMVC.onTap = { [weak self] in<br>            self?.documentController.toggle()<br>        }</pre><h3>MVVM</h3><p><strong>The ViewModel:</strong></p><pre>import Observation<br><br>@Observable<br>final class ViewModel {<br>    private let documentController: DocumentController<br><br>    var isDocSigned: Bool<br><br>    init(documentController: DocumentController) {<br>        self.documentController = documentController<br>        self.isDocSigned = documentController.isSigned<br><br>        documentController.observerMVVM = { [weak self] value in<br>            self?.isDocSigned = value<br>        }<br>    }<br><br>    var prompt: String {<br>        isDocSigned ? &quot;Undo signature&quot; : &quot;Please sign this document&quot;<br>    }<br><br>    func sign() { documentController.toggle() }<br>}</pre><p><strong>The View:</strong></p><pre>import SwiftUI<br><br>struct ViewMVVM: View {<br>    @Bindable var viewModel: ViewModel<br>    private let signatureSymbol = &quot;signature&quot;<br><br>    init(viewModel: ViewModel) {<br>        self.viewModel = viewModel<br>    }<br><br>    var body: some View {<br>        VStack {<br>            Button(viewModel.prompt) {<br>                viewModel.sign()<br>            }<br>            Image(systemName: signatureSymbol)<br>                .symbolEffect(.drawOn, isActive: !viewModel.isDocSigned)<br>        }<br>    }<br>}</pre><p>And again we examine each arrow from the architecture diagram…</p><p><strong>View — <em>data binding and commands </em>→ ViewModel</strong></p><p><strong>In MVVM the View holds a reference to the ViewModel </strong>(N.B. the direction of this dependency is the inverse of Controller → View in MVC):</p><pre>//  ViewMVVM.swift<br><br>@Bindable var viewModel: ViewModel</pre><p>When a user taps the button, the View is then free to call the ViewModel’s public method sign:</p><pre>//  ViewMVVM.swift<br><br>Button(viewModel.prompt) {<br>                viewModel.sign()<br>            }</pre><p>In this way the View invokes a command on the ViewModel in response to a user interaction event.</p><p><strong>ViewModel — <em>send notifications </em>→ View</strong></p><p>The ViewModel implements properties and commands to which the View can bind.</p><pre>//  ViewModel.swift<br><br>var isDocSigned: Bool<br>...<br>var prompt: String {<br>        isDocSigned ? &quot;Undo signature&quot; : &quot;Please sign this document&quot;<br>    }<br><br>func sign() { documentController.toggle() }</pre><p>The Observation framework is the most natural approach to binding the View to the ViewModel when implementing the View layer with SwiftUI. By marking the ViewModel class@Observable, it will automatically notify any “observers” of changes to its properties:</p><pre>//  ViewModel.swift<br><br>import Observation<br><br>@Observable<br>final class ViewModel {...}</pre><p>Since View’s body property reads the promptand isDocSigned properties from the observable ViewModel, SwiftUI automatically redraws the View whenever those properties change:</p><pre>//  ViewMVVM.swift<br><br>var body: some View {<br>        ...<br>            Button(viewModel.prompt) {...}<br>        ...<br>                .symbolEffect(.drawOn, isActive: !viewModel.isDocSigned)<br>        }<br>    }</pre><p>If you need a refresher on the magic of the Observable framework, <a href="https://developer.apple.com/documentation/SwiftUI/Managing-model-data-in-your-app">this article</a> provides a great summary.</p><p>🚨 <strong>MVVM VIOLATION </strong>🚨</p><p>It is worth noting that one of the objectives of MVVM is to keep the ViewModel agnostic to the frameworks and platforms on which the View depends. This is to ensure the ViewModel is reusable across different View implementations. By marking the ViewModel as Observable we’ve violated this requirement in its strictest form. However, this violation is considered acceptable given the prevalence of this approach when using SwiftUI. If we were to implement MVVM using UIKit, then the MVC pattern itself would be a more natural choice for binding the ViewModel to the View. This is because in UIKit a Controller in the form of a UIViewController must present the View. In this case the letters in MVC would represent the following: “M” would be the View<strong>Model</strong> from MVVM, “V” would be the View from MVVM and the “C” would be a new controller binding the two.</p><p><strong>Model — <em>send notifications </em>→ Controller</strong></p><p>The relationships between the Model and ViewModel in this MVVM implementation are almost identical to the case of MVC above, so I’ll keep the explanations brief.</p><p>The Model defines an observerMVVM callback</p><pre>//  DocumentController.swift<br><br>var observerMVVM: ((Bool) -&gt; Void)?</pre><p>which is set in the ViewModel</p><pre>//  ViewModel.swift<br><br>documentController.observerMVVM = { [weak self] value in<br>            self?.isDocSigned = value<br>        }</pre><p>and the observerMVVM callback is then called whenever the DocumentController’s isSigned state changes :</p><pre>//  DocumentController.swift<br>var isSigned: Bool {<br>        ...<br>        set {<br>            ...<br>            notify()<br>        }<br>    }<br>private func notify() {<br>        ...<br>        observerMVVM?(document.isSigned)<br>    }</pre><p><strong>ViewModel — <em>updates</em> → Model</strong></p><p>The ViewModel holds a direct reference to the Model:</p><pre>//  ViewModel.swift<br><br>private let documentController: DocumentController</pre><p>The ViewModel implements a method sign which calls the Model’s method toggle:</p><pre>//  ViewModel.swift<br><br>func sign() { documentController.toggle() }</pre><p>and as explained above, this method is called by the View in response to user interaction events</p><h3>Final thought: A comparison of dependency structures</h3><p>In MVC, the Controller knows about the View but not vice versa. In MVVM, the View knows about the ViewModel but not vice versa. The dependency diagram below compares this aspect of the two design patterns.</p><p>N.B. An arrow pointing from source object to target object means “the source object <strong>has a</strong> reference to the target object”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*UUMNOrfMCr9hh2bm9NJuig.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29a114c6513a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use SwiftData like a boss]]></title>
            <link>https://medium.com/@samhastingsis/use-swiftdata-like-a-boss-92c05cba73bf?source=rss-e84c9b3dd4e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/92c05cba73bf</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[SamHastings]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 13:22:18 GMT</pubDate>
            <atom:updated>2024-06-24T13:22:18.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*SgL7J73RPdtcqZGJn4M_rQ.jpeg" /><figcaption>Parallel tracks representing the execution threads that will deliver the train carriage of your app’s UI to the rolling green fields of responsiveness. Photo by <a href="https://unsplash.com/@phorgod?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Abbas Tehrani</a> on <a href="https://unsplash.com/photos/aerial-view-of-road-in-the-middle-of-green-grass-field-RNl71IBvrDE?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a>.</figcaption></figure><p>SwiftData’s @Query macro runs on the MainActor. For heavy workloads this can block the UI. One solution is to fetch SwiftData models on a background thread. This article provides a quick implementation that does not trigger Swift compiler concurrency warnings.</p><h3>Motivation for this article</h3><p>There’s a steep learning curve when getting your head around Swift’s concurrency model. When building my own apps I have struggled to ensure they remain performant and responsive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*qbi0GH68bHtgiVb4WOsgPA.png" /><figcaption>My Friday nights*.</figcaption></figure><p>Sometimes I manage to hack together an approach that works, but I’m too scared to turn the Swift compiler’s strict concurrency checking to “Complete”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*1rkhHVB0w65Pdyh1OgRW4A.png" /><figcaption>My Saturday nights*.</figcaption></figure><p>But ignorance is not bliss; these warnings indicate that your app may be vulnerable to concurrency related issues such as data races — not to mention that some of these warnings will become errors in future versions of Swift! It makes sense to address them now.</p><h3>Article structure</h3><p>I’m going to show you how to implement a set of components which together will allow you to fetch large numbers of SwiftData models on a background thread in a thread-safe way. This article will present the implementation sequentially in the following sections:</p><ol><li><strong>SwiftData model ;</strong></li><li><strong>ModelActor;</strong></li><li><strong>ViewModel</strong> <strong>and</strong> <strong>View</strong>.</li></ol><p>The code for the entire project can be found in this <a href="https://github.com/SamHastings1066/SwiftDataInBackground">GitHub repo</a>.</p><p>In case you read the code and are wondering “Yeah, but how do you create and persist the SwiftData models in the first place?” Fear not. The <a href="https://github.com/SamHastings1066/SwiftDataInBackground">full project</a> includes additional code to create and persist a large amount of SwiftData models on a background thread in a thread-safe way.</p><p>Two more things before we get started:</p><p>(i) This article assumes a basic understanding of <a href="https://developer.apple.com/xcode/swiftdata/">SwiftData</a>, Swift actors and the <a href="https://developer.apple.com/documentation/swift/sendable">Sendable</a> protocol. For a great explanation of Swift actors check out:</p><p><a href="https://medium.com/@valentinjahanmanesh/swift-actors-in-depth-19c8b3dbd85a">Swift Actors — in depth</a></p><p>(ii) I’m going to be referring to different Swift compiler warnings throughout this article. If you are coding along and want to see these warnings for yourself you will need to make the following change to your Xcode project settings: select your project, go to the “Build Settings” tab, search for “concurrency” and <strong>set “Strict Concurrency Checking” to “Complete”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*I3GRBV_69aIf3eY1x7PK7Q.png" /></figure><p>OK, let’s get cracking.</p><h3>1. SwiftData model</h3><p>First we set up a SwiftData model calledUser:</p><pre>// User.swift<br>import Foundation<br>import SwiftData<br><br>@Model<br>class User {<br>    let id: UUID<br>    let name: String<br>    <br>    init(id: UUID = UUID(), name: String) {<br>        self.id = id<br>        self.name = name<br>    }<br>}</pre><p>Our objective is to fetch a large number of these User models on a background actor — i.e. without blocking the main thread — and once fetched, to pass them over to the MainActor in order to update the app’s UI. This is known as crossing the “actor boundary” (i.e. passing values from one actor to another).</p><p><strong>SwiftData models and the Sendable protocol</strong></p><p>Marking types as Sendable tells the Swift compiler that their values can be safely shared across threads of execution. This means their values can be passed across the boundary between the MainActor and a background actor.</p><p>However, if in anticipation of our desire to pass User values across the actor boundary we make the class final and simply try to mark it with the Sendable protocol, we get the following warning in Xcode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*Dvbj5H1mMJaCrmfh_1TfPw.png" /></figure><p>This is because the @Model macro automatically adds a var _id to any class it annotates. Classes with variable stored properties cannot be Sendable since sharing mutable state across actors could lead to data races. In any event, the general rule is that SwiftData models are not Sendable. So if we want to send their values across the actor boundary we will need another approach. This is where a data transfer object (DTO) class comes in:</p><pre>// User.swift<br>final class UserDTO: Sendable, Identifiable {<br>    let id: UUID<br>    let name: String<br>    <br>    init(id: UUID, name: String) {<br>        self.id = id<br>        self.name = name<br>    }<br>}</pre><p>The purpose of this class is simply to pass the data we need from the User model across the actor boundary. Since all of the stored properties of UserDTO are immutable (i.e. let constants), the class conforms to the Sendable protocol without any warnings.</p><h3>2. ModelActor</h3><p>Next we create a ModelActor for managing SwiftData workloads on a background thread:</p><pre>// ThreadsafeBackgroundActor.swift<br><br>import Foundation<br>import SwiftData<br><br>@available(iOS 17, *)<br>@ModelActor<br>actor ThreadsafeBackgroundActor: Sendable {<br>    <br>    private var context: ModelContext { modelExecutor.modelContext }<br>    <br>    func fetchData() async throws -&gt; [UserDTO] {<br>        let fetchDescriptor = FetchDescriptor&lt;User&gt;(sortBy: [SortDescriptor(\User.name)])<br>        let users: [User] = try context.fetch(fetchDescriptor)<br>        let userDTOs = users.map{UserDTO(id: $0.id, name: $0.name)}<br>        return userDTOs<br>    }<br>    <br>}</pre><p>Note that the fetchData method retrieves User models and converts them to UserDTO objects so that they may safely cross the actor boundary.</p><h4>What does @ModelActor do?</h4><p>If you right-click the @ModelActor macro in Xcode and select “Expand Macro” you will see that the following boiler-plate has been added to the actor:</p><pre>// ThreadsafeBackgroundActor.swift<br>// This code is Auto-generated by the @ModelActor annotation<br>nonisolated let modelExecutor: any SwiftData.ModelExecutor<br><br>nonisolated let modelContainer: SwiftData.ModelContainer<br><br>init(modelContainer: SwiftData.ModelContainer) {<br>    let modelContext = ModelContext(modelContainer)<br>    self.modelExecutor = DefaultSerialModelExecutor(modelContext: modelContext)<br>    self.modelContainer = modelContainer<br>}</pre><p>In SwiftData, the <strong>ModelContainer</strong> takes the schema created by @Model annotated classes and generates a database that can hold instances of those Model classes.</p><p>The <strong>ModelContext</strong> observes the changes to your models and provides many of the actions to operate on them. Specifically, it is the interface for fetching data and saving changes. Since it has the power to mutate the state of SwiftData models, the ModelContext is not Sendable, and therefore to ensure that the operations performed by any ModelContext are thread safe, <strong>ModelContexts cannot be shared between actors</strong>.</p><p>However, since a ModelContainer does not mutate model states, it is Sendable. That is why in the above boiler-plate code, it is ok to initialize the ModelActor with a ModelContainer which has been created outside of this actor (in this case on the MainActor).</p><p>The initializer sets up a DefaultSerialModelExecutor — this object performs SwiftData operations using the actor-isolated ModelContext created within the actor. This executor ensures that the operations performed by the ModelContext are done serially — one-by-one — thus preventing models managed by SwiftData from being corrupted by concurrent operations.</p><h3>3. ViewModel and View</h3><p>Now we can define a ViewModel with an async function backgroundFetch. This function performs SwiftData model fetches off the main thread using the ModelActor we just implemented. We make this ViewModel Sendable to let the Swift compiler know that it can be safely shared across contexts:</p><pre>// UserQueryView.swift<br><br>import SwiftData<br><br>@Observable<br>final class UsersQueryViewModel: Sendable { <br>    <br>    let modelContainer: ModelContainer<br>    <br>    init(modelContainer: ModelContainer) {<br>        self.modelContainer = modelContainer<br>    }<br>    <br>    func backgroundFetch() async throws -&gt; [UserDTO] {<br>        let backgroundActor = ThreadsafeBackgroundActor(modelContainer: modelContainer)<br>        let result = try await backgroundActor.fetchData()<br>        return result<br>    }<br>    <br>}</pre><p>We then implement a SwiftUI View with a button to trigger the background fetch, and a List view to display the results:</p><pre>// UserQueryView.swift<br>import SwiftUI<br>struct UsersQueryView: View {<br>    let modelContainer: ModelContainer<br>    @State var isFetchingUsers = false<br>    @State private var users: [UserDTO] = []<br>    var viewModel: UsersQueryViewModel<br>    <br>    <br>    init(modelContainer: ModelContainer) {<br>        self.modelContainer = modelContainer<br>        viewModel = UsersQueryViewModel(modelContainer: modelContainer)<br>    }<br>    <br>    var body: some View {<br>        VStack {<br>            Button(&quot;Background retrieval&quot;) {<br>                isFetchingUsers = true<br>                Task {<br>                    users = try await viewModel.backgroundFetch()<br>                    isFetchingUsers = false<br>                }<br>            }<br>            .buttonStyle(.bordered)<br>            <br>            if isFetchingUsers {<br>                List {<br>                    Text(&quot;Fetching users...&quot;)<br>                }<br>            } else {<br>                if users.count == 0 {<br>                    ContentUnavailableView(&quot;No Users fetched&quot;, systemImage: &quot;person.crop.circle.badge.exclamationmark&quot;)<br>                } else {<br>                    List(users) { model in<br>                        Text(model.name)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Since the ViewModel’s fetchData method is defined on an actor, it can only be called outside of the actor using the await keyword. This means it must be called within an asynchronous context — this is why the function backgroundFetch that calls it is asynchronous. The backgroundFetch itself is called from the View within a detached Task which will suspend while the function does its work on a background thread. When the function returns, it passes a value from the background actor to a variable users defined on the MainActor. This is why the ViewModel must be Sendable.</p><p>We could have defined the backgroundFetch function within the SwiftUI View in which it is called, but then that View itself would have to be Sendable. That would preclude the View from having any mutable state which may not give you the flexibility you need. However, having a separate ViewModel is a design choice and not strictly necessary.</p><p>What is strictly necessary is that the ThreadsafeBackgroundActor be initialized off the main thread. This in turn ensures that its stored property modelContext is run off the main thread, which is the reason why we created the ThreadsafeBackgroundActor in the first place — to keep our UI responsive while SwiftData work is being done in the background. For example, if you were to create the ThreadsafeBackgroundActor within the View’s initializer and then pass it as an attribute to the ViewModel’s backgroundFetch function, the fetchData function would be executed on the MainActor, potentially blocking the UI.</p><h4>Aside: Don’t set task priority to “.background”!</h4><p>Some tutorials recommend explicitly setting the priority of detached tasks to “.background”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*JHlmd-P5zpd38_p_CEyOpA.png" /></figure><p>In this case it will result in a significant hit to performance — in my testing it made fetching take <strong>five times as long!</strong> So don’t do this ;)</p><h3>Conclusion</h3><p>Our demo app successfully fetches a large amount of SwiftData models on a background thread without blocking the UI and without triggering any concurrency warnings from the Swift compiler!</p><p>In the GIF below you can see the app in use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FjjKhsvvwxWUeTU529rx5w.gif" /></figure><p>Notice that when the “Background retrieval” button is pressed, it immediately releases. However, when the “Main thread retrieval” button is pressed, it only releases at the moment the models are returned — suggesting the main thread was blocked during retrieval.</p><p>This is confirmed by the corresponding readout from Instruments when the app is profiled as the operations in the GIF are performed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*bSlzsAEg0pPFPbpLPVxQjg.png" /></figure><p>The first large block of blue lines in the Time Profile instrument is not associated with any hangs. This corresponds to the background fetch. However, the Hangs instrument displays a “Severe hang” alongside the second large blue block — corresponding to the main thread fetch blocking the UI.</p><p>The entire implementation of this app can be found in my <a href="https://github.com/SamHastings1066/SwiftDataInBackground">GitHub repo for this project</a>.</p><p>Thanks, and if you enjoyed reading please like the article, or follow me, or both!</p><p>* Disclaimer: my avatar was generated by DALL-E and does not resemble me — he is far better looking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92c05cba73bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>