'SwiftUI + Core Data crash when using `.allObjects` of a "To Many" relationship entry

I am constantly getting crash reports with a stack trace like this:

0   libobjc.A.dylib                 0x0000000199e6a334 object_getMethodImplementation + 48 (objc-object.h:97)
1   CoreFoundation                  0x00000001853d35a4 _NSIsNSSet + 40 (NSObject.m:381)
2   CoreFoundation                  0x00000001852a6888 -[NSMutableSet unionSet:] + 108 (NSSet_Internal.h:56)
3   CoreData                        0x000000018b4af3b0 -[_NSFaultingMutableSet willReadWithContents:] + 636 (_NSFaultingMutableSet.m:167)
4   CoreData                        0x000000018b53c3a0 -[_NSFaultingMutableSet allObjects] + 32 (_NSFaultingMutableSet.m:340)

My code is doing the following, this is inside the Core Data auto generated class (I am using the code bellow inside an extension I have made to that class):

if let tasks = tasks?.allObjects as? [Task] {
}

where tasks are @NSManaged public var tasks: NSSet?, this is the "array" object from core data (the auto generated one).

Any ideas what is wrong here, maybe it is a Core Data issue itself, SwiftUI + Core Data for some reason.



Solution 1:[1]

This is the way I do it, as a computed property in the class extension, and never had issues.

var allTasks: [Task] {
tasks?.allObjects as? [Task] ?? [ ]
}

you could add the if let inside and do any sorting or filtering and return that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1