Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

objective c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...