Core Data: Id is set but showing up as nil when saving

Viewed 409

When saving a Core Data entity in Xcode 11.4.1, the error tells me a property is nil even though I just set it (and printing shows this). The code I run is:

let res = Result(context: context)
res.completionTime = NSDate() as Date
res.value = value
res.id = UUID()
res.parentRow = self.row

print(res)

do {
    try context.save()
} catch {
    print(error)
}

And the Result is defined through:

extension Result {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Result> {
        return NSFetchRequest<Result>(entityName: "Result")
    }

    @NSManaged public var completionTime: Date?
    @NSManaged public var value: Int16
    @NSManaged public var id: UUID?
    @NSManaged public var parentRow: Row?

}

In the print statement, I see that id and parentRow are set.

<Result: 0x6000035aa710> (entity: Result; id: 0x60000166e4c0
<x-coredata:///Result/tDEBC3DA1-6A05-4150-9EB4-BFD4A79A94E52>;
data: {
    completionTime = "2020-05-16 19:38:47 +0000";
    id = "E557C8E4-A64F-4C83-9774-F2C2A19C1697";
    parentRow = "0xa82f7a0d615a81bc
<x-coredata://F6AEF455-DF4A-4A39-9353-FF0AE5189A8D/Row/p35>";
    value = 5;
})

But the error tells me that id and parentRow are nil. Other properties like value are set. What's causing this?

Error Domain=NSCocoaErrorDomain Code=1560 "Multiple validation errors occurred."
UserInfo={NSDetailedErrors=(
    "Error Domain=NSCocoaErrorDomain Code=1570 \"id is a required value.\"
UserInfo={NSValidationErrorObject=<Result: 0x6000035a80a0> (entity: Result; 
id: 0xa82f7a0d61d281be <x-coredata://F6AEF455-DF4A-4A39-9353-FF0AE5189A8D/Result/p1>;
data: {\n    completionTime = \"2020-05-16 19:03:14 +0000\";\n    
id = nil;\n   
parentRow = nil;\n    value = 5;\n}), NSValidationErrorKey=id,
NSLocalizedDescription=id is a required value.}",
    "Error Domain=NSCocoaErrorDomain Code=1570 \"parentRow is a required value.
\" UserInfo={NSValidationErrorObject=<Result: 0x6000035a80a0> (entity: Result; id: 0xa82f7a0d61d281be <x-coredata://F6AEF455-DF4A-4A39-9353-FF0AE5189A8D/Result/p1>; 
data: {\n
  completionTime = \"2020-05-16 19:03:14 +0000\";\n  
  id = nil;\n
  parentRow = nil;\n
  value = 5;\n
}), 
NSValidationErrorKey=parentRow,
NSLocalizedDescription=parentRow is a required value.}"
)}
1 Answers

I had this issue, and then I realised that one of my inverse relationships was to-one when it should have been to-many, with the delete rule set to Nullify, so when I set a second object to have that relationship, it probably assumed the previous object was no longer related, and nullified that relationship. So perhaps the inverse relationship to parentRow (e.g. a 'childRows' in your Row entity) has the type To One instead of To Many (check in the Data Model Inspector for the relationship) and the parentRow is being set to nil whenever some other row is given the same parent.

Related