ModelActor + SwiftData

Hello all I have a question with ModelActor, this my model, I have N conversation and we have N User

@Model
class Conversation {
    @Attribute(.unique)
  
    var id: UUID
    var name: String
    var user: User
    var messages: [Message]
    
  init(name: String) {
    self.id = UUID()
    self.name = name
  }
}

@Model
class User {
    @Attribute(.unique)
  
    var id: UUID
    var name: String
    
  init(name: String) {
    self.id = UUID()
    self.name = name
  }
}

and to avoid dataRace I want to use @ModelActor macro

If I understand correctly, this will allow me to serialize my calls in the database.
But should I have one ModelActor or two ModelActor ?

One ModelActor will managed all my insert and get, like this I am sure that all my insert and get are serialized and we have no DataRace

@ModelActor
actor DataBase {
  static let shared = DataBase()
  
  private init?()  {
    guard let modelContainer = try? ModelContainer(for: Conversation.self, User.self) else { return nil }
    self.init(modelContainer:modelContainer)
  }
  
  
  func newUser() {
    modelContext.insert(User(name: "name"))
    try? modelContext.save()
  }
  
  func getUser() {
    let descriptor = FetchDescriptor<User>()
    let value =  try? modelContext.fetch(descriptor)
  }
  
  func newConvesation() {
    
  }
  
  func getAllConversation() {
    
  }
}

But I want to split my code and avoid to have a big DataBase class

There is a way to split my DataBase to UserDataBase and ConversationDataBase, and be sure to be alway serialized ?

I was thinking to have 2 ModelContainer:

let modelContainer = try? ModelContainer(for: Conversation.self)

and

let modelContainer = try? ModelContainer(for: User.self)

in 2 DataBase actor but If I do like this, conversation can keep a reference with user ? I was not sure ?

I don't know what is the best solution here

Or I need to keep all my code in one actor if I want to user ModlActor

Thanks in advance

1 Like

I may be wrong, just for reference.

One or two ModelActors don't matter, you can write different functions, and you already did it.
You have relationships with User and Conversation, so you must put them into one container.