1

You can insert one object at a time in the model context by doing this:

modelContext.insert(object)

If I want to insert an array of objects, I would do this:

for obj in objects {
    modelContext.insert(obj)
}

This works but seems ineficient. Is there a way to directly insert or append a full array of objects into the model context?

2
  • 2
    No. There is not Commented Nov 23, 2023 at 1:26
  • I think there is a workaround, like making another class that has an array of persistent models inside. However, this wrapper class can't be used with @Query. Commented Nov 23, 2023 at 2:17

1 Answer 1

4

According to Apple's Documentation, the default value for isAutosaveEnabled is true.

"the returned context periodically checks whether it contains unsaved changes, and if so, implicitly saves those changes on your behalf"

Consider the following optimizations:

  1. Turn off auto-saving: Change the isAutosaveEnabled to false.
  2. Wrap Inserts in a Single Transaction: Use modelContext.transaction {} to group your insertions into a single transaction. This can significantly improve performance compared to multiple transactions if you're dealing with large quantity of objects.
  3. Reduce Save Frequency: Instead of saving the context after each insertion, save it once after all insertions are complete. This reduces the overhead of writing to the disk.

Example:

modelContext.transaction {
    for obj in objects {
        modelContext.insert(obj)
    }
    do {
        try modelContext.save()
    } catch {
        // Handle error
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.