简体   繁体   中英

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?

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.

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.

That's a subjective question. You can also set them up as a linked list in the order you want them in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM