ModelActor Implementation Changes In Xcode 15 Beta 7

Hi all,

There appears to be some changes to how ModelActors are implemented in Beta 7 of Xcode 15. In Beta 6, we had the DefaultModelExecutor object which we used to assign to the ModelActor's executor property. A simple example is shown below:

final actor SimpleModelActor: ModelActor {
    let executor: any ModelExecutor
    
    init(modelContainer: ModelContainer) {
        let modelContext = ModelContext(modelContainer)
        executor = DefaultModelExecutor(context: modelContext)
    }
    
    func addItem() {
        let newItem = Item(timestamp: Date())
        context.insert(newItem)
        try! context.save() 
    }
....
}

However, it seems that the DefaultModelExecutor class has been removed for Beta 7, without any real replacement. Anyone know how to implement a ModelActor in the new beta?

Thanks in advance.

Answered by Fat Xu in 762606022
@ModelActor
actor CountryModelActor {
    init(container: ModelContainer) {
        modelContainer = container
        let context = ModelContext(container)
        modelExecutor = DefaultSerialModelExecutor(modelContext: context)
    }
    
    func newItem() {
        let item = Item(timestamp: .now, name: "\(Int.random(in: 0...3))")
        modelContext.insert(item)
        try! modelContext.save()
    }
}
Accepted Answer
@ModelActor
actor CountryModelActor {
    init(container: ModelContainer) {
        modelContainer = container
        let context = ModelContext(container)
        modelExecutor = DefaultSerialModelExecutor(modelContext: context)
    }
    
    func newItem() {
        let item = Item(timestamp: .now, name: "\(Int.random(in: 0...3))")
        modelContext.insert(item)
        try! modelContext.save()
    }
}

Actually you can skip the constructor.

@ModelActor
actor CountryModelActor {
    func newItem() {
        let item = Item(timestamp: .now, name: "\(Int.random(in: 0...3))")
        modelContext.insert(item)
        try! modelContext.save()
    }
}

You will get an error Invalid redeclaration of 'init(modelContainer:)' if you define init(container: ModelContainer). Its being created automatically by macro now.

ModelActor Implementation Changes In Xcode 15 Beta 7
 
 
Q