Inserting array of model objects using modelContext

Hi,

I saw many examples on how to insert one model object at a time in SwiftData using modelContext.insert() , but can that command insert an array of objects in one batch as well ?

-- Kind Regards

AFAIK, there is not.

But it is really easy to build it (even as extension) by calling insert in a loop on all objects.

Get some additional advice here for performance optimisation: https://stackoverflow.com/questions/77533881/how-do-you-insert-an-array-of-objects-into-the-swiftdata-modelcontext

modelContext.transaction {
    for obj in objects {
        modelContext.insert(obj)
    }
    do {
        try modelContext.save()
    } catch {
        // Handle error
    }
}
Inserting array of model objects using modelContext
 
 
Q