SwiftData: Accessing a context outside of a view not possible.

Getting a warning from the Xcode compiler about accessing a context outside of a view. It popped up in white text on a purple background, not the usual white on yellow warning color.

The actual warning text is: Accessing Environment<ModelContext>'s value outside of being installed on a View. This will always read the default value and will not update.

This seems to mean that any datastore access must be done within a view, and isn't possible from the model or some sort of DataManager class. Am I reading this correctly? I'm trying to keep the business logic out of the views. I can do it with everything except the datastore code because of this context issue. Doesn't seem to make sense.

Suggestions greatly appreciated.

Post not yet marked as solved Up vote post of OldBrian Down vote post of OldBrian
1.9k views
  • I hope this will help or at least provide hints: https://www.hackingwithswift.com/forums/swift/trying-to-access-managed-object-context-through-a-model/23266

Add a Comment

Replies

I am running into this same problem. Did you ever resolve this?

Receiving the same warning with:

import SwiftData

@MainActor class…: ObservableObject {
@Environment(\.modelContext) private var modelContext
init() {
let descriptor = FetchDescriptor<Location>(predicate: #Predicate {$0.areaName != ""})
let count = (try? modelContext.fetchCount(descriptor)) ?? 0 <<== Warning here
}}

Then the App Crashes

  • Not interested in a View with a List
  • Just a [fetchCount]