views:

129

answers:

2

I've been trying to come up with a way to solve my problem, but every solution I can think of is messy and makes me want to retch.

I have a one-to-many relationship, consisting of a Team object that can have many Member objects. When I built my data model using Xcode, I was given the default NSSet in which to store the member objects, Unfortunately Sets are not ordered and I need to preserve the order of the Member objects and I need to know if there are empty spaces between Members.

I thought of Using an NSArray in place of the NSSet and creating a dummy Member object in my data store that I could use to mark vacant a spot between to Member objects, but that solution really feels like too much of a hack to me. Since I'll always have to filter out this dummy Member from any queries.

An NSDictionary would be perfect as I could store the Member object references and their positions as Object-Key pairs, (taking care of both order and vacancies) but apparently CoreData does not support NSDictionary.

Has anyone had a similar need, and devised a simple solution?

+2  A: 

The lack of ordered Core Data to-many relationships is an artifact of the underlying database design. The reasons for this, along with potential solutions, are discussed in this Cocoa mailing list thread. Solutions include adding an index property to your managed objects or maintaining these objects in a linked list.

If you don't want to do this yourself, Brian Webster has put together an implementation of ordered to-many Core Data relationships here.

Finally, if you are looking to switch away from Core Data, Aaron Hillegass' new BNRPersistence framework supports ordered relationships.

Brad Larson
Apparently my googlefu is weak today. Thanks or pointing me in the right direction. Brian's ordered to-many solution looks like exactly what I need.
Eric Schweichler
+2  A: 

Ordered relationships are trivial to implement. Here's the code I did for one of NSManagedObject subclasses.

(For some reason, I can't post formatted code to Stackoverflow today.)

In this case I've got a relationship set up like:

AlphaEnity<-->>AlphaToBetaEntity<<-->BetaEntity

The AlphaToBetaEntity has an order Attribute. I sort the AlphaToBetaEntity and then return the linked BetaEntity as needed. It's like doing a pointer sort in old school C.

It has the advantage of being blistering fast on very large sets and you don't have to fault in the BetaEntity until you need to read an attribute from it.

TechZen
Just an update: I finally got around to implementing your solution. At first I thought I would go with the recommendations above, but your solution turned out to be a better fit for my relationships. Having an intermediate ordering object turned out not to be as horrible as I thought since it fits in the context of my data model, Thanks! I wish I could mark two solutions as accepted!
Eric Schweichler