Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preserve an ordered list in Core Data

I'm writing an API method that returns a list of objects from a web service. This service also caches results and attempts to return the cached results (if any) before hitting the web service again. So I'm storing this list in a Core Data entity. But Core Data only allows to-many relationships to be stored in an NSSet, which does not preserve order. But I want the cached results to retain the original order (which was originally from the web service). I don't necessarily know how that order is established (so I can't sort).

So how can I preserve this order? My plan is to store a string with the object ids which I can later use to order them:

NSString *objectIds = @"1 5 2 9 4";

Is this the best way to do it?

like image 343
caleb Avatar asked Jan 05 '12 21:01

caleb


2 Answers

If you can target iOS 5 then you can use the new NSOrderedSet feature for arbitrarily-ordered Core Data relationships. See the Core Data Release Notes for iOS 5 for more information about this new feature.

If you have to support iOS 4 then you will need to handle the ordering yourself. A common way to do this is to add an integer property to your model which you then need to manage yourself. You can then sort on this property when fetching your data.

Storing the order in a completely different string seems like the wrong way to do it. If the ordering is important this information should be in the model and the user should be able to query for it directly ("give me the first five objects of this particular list", or "what is the index of object foo"). Having to get a string of object IDs, parse it, and then query for certain object IDs feels very wrong to me.

like image 63
Sebastian Celis Avatar answered Nov 01 '22 14:11

Sebastian Celis


Include an NSNumber id field of your own in the CoreData model in which you are storing the objects. The id will represent the ordering you want to preserve; you'll have to set it yourself, obviously. Then when you fetch the objects from CoreData you can do so sorted by that id. You may want/have to maintain somewhere the highest id value you've assigned to retain ordering correctly with subsequent web service calls and app launches.

like image 27
Mark Granoff Avatar answered Nov 01 '22 15:11

Mark Granoff