开发者

How to efficiently get all instances from deeper level in Cocoa model?

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 开发者_如何学Goin 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. 


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:@"bObjects.@distinctUnionOfSets.cObjects"];

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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜