Core Data - How to check if an object relationship exists without firing a fault
Asked Answered
S

2

7

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?

Smelt answered 16/11, 2013 at 13:18 Comment(0)
R
9

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.

Ringleader answered 16/11, 2013 at 14:13 Comment(1)
Thanks, that makes sense. I thought that objectA.relationshipToB would cause an automatic fault but I am glad to see that it does not.Smelt
S
0

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 `?`
Sidonius answered 20/5, 2015 at 18:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.