I am using the following tutorial to implement Core Data into my Swift IOS application. As shown in the video, my persistance manager is created via a singleton pattern. Here is the code that describes it:
import Foundation
import CoreData
class DataLogger {
private init() {}
static let shared = DataLogger()
lazy var context = persistentContainer.viewContext
private var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "mycoolcontainer")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func save () {
if self.context.hasChanges {
self.context.perform {
do {
try self.context.save()
} catch {
print("Failure to save context: \(error)")
}
}
}
}
}
Now, if I create a loop with around 1000 or so elements of my entity ( MyEntity is the Core Data entity object ) with the following code, the application crashes.
class MySampleClass {
static func doSomething {
for i in 0 ..< 1000 {
let entry = MyEntity(context: DataLogger.shared.context);
// do random things
}
DataLogger.shared.save()
}
}
It crashes on MyEntity(context: DataLogger.shared.context), and I am unable to observe any logs to see why. Occasionally, it will reach the save() call and succeed or crash with the the generic error that states:
Heap corruption detected, free list is damaged at 0x280a28240 *** Incorrect guard value: 13859718129998653044
I've tried to look around the net to find any hints as to what the issue could be. I've tried to make the save() method in the DataLogger synchronized, via .performAndWait(), and saw no success. I also tried to use childContexts to perform the same, with no success, via this code:
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = context
childContext.hasChanged {
childContext.save();
}
I suspect that I am implementing the DataLogger class incorrectly but cannot observe what the actual issue might be. It might be related to the quantity of created objects, or possibly threading, but I am not certain. What would be the correct way to implement the DataLogger class to ensure any other class can use it and store the entities to disk?