Ordered Arrays for Core Data managed objects

First of all, I am clear about the rationale behind apple not providing ordered arrays for core data objects. However, there *are* situations when you need one. The common solution (adding a order-by attribute to the objects you intend to store) was too intrusive for my case. After long hours of googling, the best-case solution I found was http://www.fatcatsoftware.com/blog/2008/per-object-ordered-relationships-using-core-data but that too was not to my taste.

So I went about and have developed my own workaround to the problem. Here is how you’d use it -

1. Derive your Managed Object (in which you want to add an array) from the MRManagedObjectWithArray class.

2. Add an Transformable attribute for each array that you wish to add.

3. In your app delegate’s applicationDidFinishLaunching, register the custom Value Transformer by calling [MRManagedObjectWithArrayTransformer registerTransformer];

4. Access your arrays with |arrayForKey| and |mutableArrayForKey|.

For example,

[[you mutableArrayForKey:@"beers"] addObject:[Beer pint]];

if( [[you arrayForKey:@"beers"] count] > 7 ) NSThink(@”I’m drunk!”);

You can get the code at http://gitorious.org/mrmanagedobjectwitharray/code/archive-tarball/master

or browse it online at the public VCS http://gitorious.org/mrmanagedobjectwitharray/

My intention of posting this here is so that I can get some feedback (and hopefully code improvements!) from you guys. I think the implementation is complex, but the interface is very simple. There are no unnecessary writes, and only a single copy of the array is maintained (contrast with the other solutions on the net – most of which copy the entire array each time a modification is made).

Related Posts

Leave a Reply