views:

52

answers:

2

In my Cocoa Mac app I have an instance A which contains an unordered set of instances B which in turn has an ordered set of instances C. An instance of C can only be in one instance B and B only in one A.  

I would like to have an unordered set of all instances C available on instance A. I could enumerate over all instances B each time, but that seems expensive for something I need to do often. However, I am a bit worried that keeping track of instances C in A could become cumbersome and be the cause of  inconsistencies, for example if an instance C gets removed from B but not from A

Solution 1 – Use a NSMutableSet in A and add or remove C instances whenever I do the same operation in B

Solution 2 – Use a weak referenced NSHashTable in A. When deleting a C from B it should disappear for A as well. 

Solution 3 – Use key value observing in A to keep track of changes in B, and update a NSMutableSet in A accordingly. 

Solution 4 – Simply iterate over all instances B to create the set whenever I need it.  

Which way is best? Are there any other approaches that I missed? 

NB I don't and won't use CoreData for this app. 

A: 

If you don't really needs to optimize your code, you shouldn't bother with caching: enumerate over all instances of B each time you need your set.

mouviciel
+1  A: 

If A has a set of B objects, and each B object has a set of C objects, you can do:

NSSet * allCObjectsInA = [anAObject valueForKeyPath:@"[email protected]"];

This is assuming that you can access A's B objects via a method called - (NSSet *) bObjects;, and B's C objects with -(NSSet *) cObjects;

Dave DeLong
Thanks for this pointer. Those set and array operators are indeed a good option I had overlooked. As `B` contains an array of `C` I'd probably go with another operator than `@distinctUnionOfSets`, probably `@unionOfArrays`.
Johan Kool
Correction, I had to use `@distinctUnionOfArrays`, as the `@unionOf...` operators can only be used on an array, not a set. Anyway, thanks again for this neat solution.
Johan Kool