i am developing a SwiftUI App, where i need to work with relatively large amounts of data sets. While processing these data i had some issues with my app crashing randomly. As i was debugging this situation for a while i found out that dataraces were the cause for these crashes. That is why i decided to use an actor for these things.. As the actor takes care of concurrent threads, i was not having any crashes anymore, BUT, now i have to deal with some memory leaks! i've created a simple demo project to reproduce these leaks.
my view:
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
// @Query private var items: [Item]
var body: some View {
VStack {
Button(action: {
Task { await testImport() }
}, label: {
Text("Import")
})
}
}
}
the function:
func testImport() async {
let actorX = testActor(container: self.modelContext.container)
await actorX.cleanUp()
// create dummy data:
var dummyArray: [Int] = []
for i in 0...1300 {
dummyArray.append(i)
}
await actorX.saveAssets(with: dummyArray)
dummyArray = []
print("Checkpoint")
}
the actor:
actor testActor {
public var modelContainer: ModelContainer
public var modelExecutor: any ModelExecutor
private var context: ModelContext { modelExecutor.modelContext }
public init(container: ModelContainer) {
self.modelContainer = container
let context = ModelContext(modelContainer)
modelExecutor = DefaultSerialModelExecutor(modelContext: context)
}
func cleanUp() {
print("starting cleanup...")
do {
try context.delete(model: Item.self)
print("cleanup: table LocalAsset truncated")
} catch {
print("Failed to clear all LocalAsset data.")
}
}
func saveAssets(with array: [Int]) {
for i in 0..<array.count {
let foo = array[i]
let newItem = Item(timestamp: Date(), dummyInt: foo)
context.insert(newItem)
}
try? context.save()
}
}
And Here's a screenshot of Xcode's Instruments Leak tool:
i hope somebody has any idea how to get rid of those leaks..