views:

393

answers:

2

I have a CoreData entity (waypoint) with a foreign key to another entity (track). When the foreign key is set, or if it is not set, this if statement works fine:

if ([wp track]) {
  thirdLabel.text = [NSString stringWithFormat:@"Part of Track: %@", [[wp track] title]];
}

However, if the track that the waypoint is keyed to has been deleted, then [wp track] still evaluates to true, and the program crashes when I set the label text.

So, how do I properly check for this "has been deleted" null value in CoreData?

A: 

It is valid Objective-C to send messages to nil. You'll need to modify your if predicate to read:

if (wp != nil && [wp track]) {
    //...
}

You can also check the retainCount of an object, which might return 0 or crash in the case when the object has been deallocated.

In either case, it might be best to send out some kind of notification from whomever destroyed wp to those interested in using it, or at least retain wp until after you're done with it in this code.

fbrereto
That doesn't change the current behavior, as sending a message to nil returns nil, which would fail the 'if' condition.
bobDevil
+6  A: 

It sounds like you have an issue with a one-way relationship. The problem you are describing is given in more detail here under "Unidirectional Relationships"

Basically, your waypoint has no way to know that the track was deleted out from under it. The recommended solution is to model the relationship to be bi-directional, which allows Core Data to maintain consistency in your model.

In your specific example, if your 'track' object has an inverse relationship back to the 'waypoint', then when you delete the 'track' object, Core Data will know to update the waypoint to get rid of any dangling relationships. More about this can also be seen at the above link.

bobDevil