views:

43

answers:

1

I'm trying to figure out if the KVC mechanisms provide any sort of help when dealing with relationship properties which are inverse relationships of each other. I'll use the contrived and standard Department/Employee example.

@interface Department : NSObject {
      NSMutableArray *employees;
}
@property (retain) NSMutableArray *employees;
// KVC methods for mutating the employees array

@end


@interface Employee : NSObject {
    Department *department;
}
@property (retain) Department *department;

With just this (and the omitted KVC collection methods) what kind of help does KVC provide for managing the relationship in both directions? I'm only at the conceptual stage right now. I know with Core Data I can set explicit inverse relationships and thus when I use [myDepartment insertObject:newEmployee inEmployeesAtIndex:lastIndex];, then newEmployee.department is automatically set to myDepartment, but can I achieve this with solely KVC and the runtime, or do I need Core Data?

Thanks in advance for helping.

Edit Somewhat unrelated but also important, in my code I put Employee's property to Department as being retain but I'm wondering if this will cause a retain cycle?

+1  A: 

There's nothing directly in Key-Value Coding that will help you maintain inverse relationships. You could leverage Key-Value Observing to do so however.

The main things you'll want to do are:

  • Implement your own class equivalent to NSManagedObject, rather than just subclassing NSObject directly for your entity classes, since after all you can't be guaranteed arbitrary NSObject subclasses will work with the system you come up with. (Alternatively, you could codify everything they need in a protocol. EOF did this with the EOEnterpriseObject protocol.)
  • Implement your own class equivalent to NSManagedObjectContext to handle the observation of instances of your entity classes, so it can tell them to do inverse maintenance at the appropriate time. Note that inverse maintenance triggered by KVO needs to not re-trigger KVO which would trigger inverse maintenance and so on.
  • Implement your own class hierarchy equivalent to NSManagedObjectModel so your equivalent to NSManagedObjectContext knows what properties of instances of your entity classes can have inverse relationships, and what those are.

Given all of that, you'll probably just want to use Core Data, because it already does all of that and has been extensively tuned over the years to do it quite well.

Chris Hanson
Aha, I was starting to realize this was the only way. You're right, for that effort I'd be much better off with Core Data. However, since my needs are so minor (very small object graph) I think I can just get by with doing things "by hand". Thanks for the thorough answer!
jbrennan