SwiftData: Fatal error: No backing data found for new relation

47 Views Asked by At

I have two related models with SwiftData:

@Model
class Assistant {
    var id: String
    var threadId: String
    var name: String
    var model: String
    var instructions: String
    var lastMessageDate: Date
    var messages: [Message]
    
    init(id: String, threadId: String, name: String, model: String, instructions: String, lastMessageDate: Date, messages: [Message]) {
        self.id = id
        self.threadId = threadId
        self.name = name
        self.model = model
        self.instructions = instructions
        self.lastMessageDate = lastMessageDate
        self.messages = messages
    }
}

@Model
class Message {
    var id: String
    var systemId: UUID
    var role: String
    var date: Date
    var content: String
    var assistant: Assistant?
    
    init(id: String, systemId: UUID, role: String, date: Date, content: String, assistant: Assistant? = nil) {
        self.id = id
        self.systemId = systemId
        self.role = role
        self.date = date
        self.content = content
        self.assistant = assistant
    }
}

When trying to add a new message with

let newMessage = Message(id: UUID().uuidString, systemId: UUID(), role: "User", date: Date(), content: newAssistantMessage, assistant: assistant)

I am getting the error

SwiftData/BackingData.swift:366: Fatal error: No backing data found for new relation - Optional(AncistrsAI.Assistant)

I have the feeling it was working before and suddenly stopped. Can anyone spot an error here in the relationship?

I played around a lot with IDs and also tried

@Relationship(inverse: \Message.assistant) var messages: [Message]

but nothing works here. Really frustrating.

Using XCode 15.3 and minimum deployment target is iOS17.0.

0

There are 0 best solutions below