I receive the error CoreData: fault: NULL _cd_rawData but the object is not being turned into a fault. I have looked at many questions related to this issue and they all reference thread issue, but I am doing everything on the main thread using NSPersistentContainer.viewContext.
The problem occurs when I reference an Entity attribute that is a transformable type that is a Swift array of type [Double] the first time. Subsequent accesses do not show the error. The error also does not create an overall program fault and execution continues.
Since many other questions suggest this is a thread concurrency issue, I run the program with '-com.apple.CoreData.ConcurrencyDebug 1' but when the error appears in the console no expected errors are raised from the ConcurrencyDebug flag.
The code for my fetch request is below.
I set a relation programmatically between SMLocation and FlatPricing. The array attributes of FlatPricing have the problem, but only for the first time I access a value of the attribute.
public class FlatPricing: NSManagedObject {
....
@NSManaged public var monthlyRate: [Double]?
@NSManaged public var monthlyUseCap: [Double]?
@NSManaged public var householdsAtCap: [Int]?
....
}
func fetchThenSetManagedObjects(forLocation loc: String) -> SMLocation? {
let fetchReq: NSFetchRequest<SMLocation> = SMLocation.fetchRequest()
fetchReq.resultType = .managedObjectResultType
fetchReq.predicate = NSPredicate(format: "smlName == %@",loc)
var fetchRes: [SMLocation] = [SMLocation]()
do {
fetchRes = try persistentContainer.viewContext.fetch(fetchReq)
} catch {
print("Core Data Fetch failed")
print(error)
return nil
}
// now set all the managed objects
return fetchRes[0]
}
I set the FlatPricing object like this in various parts in my code:
....
guard let smLoc = fetchThenSetManagedObjects(forLocation: currentLocation) else {
print("Fetch failed for locationSelect")
return
}
let initFlatPricing = (smLoc.value(forKey: "flatPricing") as! FlatPricing)
When I access an attribute like:
guard var h = initFlatPricing.householdsAtCap else {
return
}
h[0] = 12
The assignment triggers the error. But a subsequent assignment to that array attribute or any of the other array attributes works fine.