Core Data - How to check if an object relationship exists without firing a fault
-
21-12-2019 - |
Question
There is an object A and an Object B. Object B has one attribute that is type transformable (image), and one relationship, which is to an object A. Object A may have a relationship to one, and only one, object B, or it may not.
As I enumerate through my object A array, I want to check if each object A has an object B. But, I don't want to fire the fault for object B (which would invoke the reverse imageToData NSValueTransformer). I just want to know if it is there or not. How can I do this without bringing object B into memory?
La solution
I think you can just test
if (objectA.relationshipToB != nil) ...
This will not fire a fault for the related B
object because you don't access its properties.
Autres conseils
In Swift I got a
Could not find an overload for '!=' that accepts the supplied arguments
error. My relationship was correctly marked as optional but in the generated NSManagedObject
my @NSManaged
property didn't have a ?
after it. So this check against nil
failed. I added the ?
and then I could check for existence of the relationship.
Before (didn't work)
@NSManaged var myRelationShip: MyClass
After (worked)
@NSManaged var myRelationShip: MyClass? // <--- Added `?`